Datagrid not showing data even though its boudn - mvvm

I have a problem with my MVVM Light implementation where I have my WPF Toolkit DataGrid and Data context bound to the correct object but no data is showing up. Can someone tell me what I'm doing wrong?
Here is my code:
MainViewModel.cs
public class MainViewModel : ViewModelBase
{
private static Logger logger = LogManager.GetCurrentClassLogger();
private C.Wsi.ClientSession privateSession;
private ObservableCollection<CashAccount> _cashaccounts;
public ObservableCollection<CashAccount> CashAccounts
{
get { return _cashaccounts; }
set
{
if (_cashaccounts.Equals(value))
{
return;
}
_cashaccounts = value;
RaisePropertyChanged("CashAccounts");
}
}
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel()
{
if (IsInDesignMode)
{
// Code runs in Blend --> create design time data.
}
else
{
_cashaccounts = new ObservableCollection<CashAccount>();
// Subscribe to CollectionChanged event
_cashaccounts.CollectionChanged += OnCashAccountListChanged;
logger.Info("----- Start -----");
// Code runs "for real"
Cs.Helper.Session session = new Session();
privateSession = session.getSession();
logger.Info("Private Session: " + privateSession.GetHashCode());
logger.Info("...Connected.....");
Cs.Helper.ResultSet results = new ResultSet();
PositionBean[] pos = results.getPositions(privateSession);
logger.Info("Positions returned: " + pos.Length);
SecurityBean[] secs = results.getSecurities(privateSession);
logger.Info("Securities returned: " + secs.Length);
ArrayBuilder ab = new ArrayBuilder(pos, secs);
CashAccount c = new CashAccount();
c.qtySod = 100.00;
c.name = "Hi";
c.account = "Acct1";
c.cashAmount = 67.00;
_cashaccounts.Add(c);
RaisePropertyChanged("CashAccounts");
//this._cashaccounts=ab.joinPositionSecurities();
}
}
void OnCashAccountListChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
}
////public override void Cleanup()
////{
//// // Clean up if needed
//// base.Cleanup();
////}
}
MainWindow.xaml
<Window x:Class="CreditSuisse.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:CreditSuisse.Helper"
xmlns:dg="http://schemas.microsoft.com/wpf/2008/toolkit"
mc:Ignorable="d"
Height="301"
Width="520"
Title="Credit Suisse - Custodial Cash Application"
DataContext="{Binding Path=Main, Source={StaticResource Locator}}">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Skins/MainSkin.xaml" />
</ResourceDictionary.MergedDictionaries>
<local:VisibilityConverter x:Key="VisibilityConverter" />
<!-- DataGrid Background -->
<LinearGradientBrush x:Key="BlueLightGradientBrush" StartPoint="0,0" EndPoint="0,1">
<GradientStop Offset="0" Color="#FFEAF3FF"/>
<GradientStop Offset="0.654" Color="#FFC0DEFF"/>
<GradientStop Offset="1" Color="#FFC0D9FB"/>
</LinearGradientBrush>
<!-- DatGrid style -->
<Style TargetType="{x:Type dg:DataGrid}">
<Setter Property="Margin" Value="5" />
<Setter Property="Background" Value="{StaticResource BlueLightGradientBrush}" />
<Setter Property="BorderBrush" Value="#FFA6CCF2" />
<Setter Property="RowBackground" Value="White" />
<Setter Property="AlternatingRowBackground" Value="#FDFFD0" />
<Setter Property="HorizontalGridLinesBrush" Value="Transparent" />
<Setter Property="VerticalGridLinesBrush" Value="#FFD3D0" />
<Setter Property="RowHeaderWidth" Value="0" />
</Style>
<!-- Enable rows as drop targets -->
<Style TargetType="{x:Type dg:DataGridRow}">
<Setter Property="AllowDrop" Value="True" />
</Style>
</ResourceDictionary>
</Window.Resources>
<dg:DataGrid DataContext="{Binding MainViewModel}" ItemsSource="{Binding CashAccounts}">
Margin="5" AutoGenerateColumns="True" HorizontalScrollBarVisibility="False">
<dg:DataGrid.Columns>
<dg:DataGridTextColumn Binding="{Binding account}" Header="Account Code" />
<dg:DataGridTextColumn Binding="{Binding name}" Header="Security Name" />
<dg:DataGridTextColumn Binding="{Binding cashAmount}" Header="Quantity Start of Day" />
<dg:DataGridTextColumn Binding="{Binding price}" Header="Cash Delta (Price Delta)" />
<dg:DataGridTemplateColumn Header="Action">
<dg:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content="Get" Visibility="{Binding cashChanged, Converter={StaticResource VisibilityConverter}}" Background="Red" />
</DataTemplate>
</dg:DataGridTemplateColumn.CellTemplate>
</dg:DataGridTemplateColumn>
</dg:DataGrid.Columns>
</dg:DataGrid>

When you do DataContext="{Binding Path=Main, Source={StaticResource Locator}}" in your Window and after DataContext="{Binding MainViewModel}" in the Datagrid, WPF tries to bind to a property named MainViewModel on your MainViewModel class which will fail. You can confirm this by looking for the binding error in the Output window in VS.
Just remove DataContext="{Binding MainViewModel}" from the DataGrid and it should work.
EDIT:
There is an extra closing > at the end of the first line in your XAML:
<dg:DataGrid DataContext="{Binding MainViewModel}" ItemsSource="{Binding CashAccounts}">
Margin="5" AutoGenerateColumns="True" HorizontalScrollBarVisibility="False">
It should be:
<dg:DataGrid DataContext="{Binding MainViewModel}" ItemsSource="{Binding CashAccounts}"
Margin="5" AutoGenerateColumns="True" HorizontalScrollBarVisibility="Disabled">
Note: False is not a valid value for HorizontalScrollBarVisibility it supports Auto, Disabled, Hidden, Visible
But I don't know why WPF throws Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead for your original XAML instead of some more meaningful error.

Related

WinUI3 and Drag and Drop

I am trying to get Drag and Drop working with WinUI3. In WPF I used to add added both AllowDrop and Drop to a UI element and I was able to receive the filename of a dropped file. However in WinUI3 the method Drop is not beeing executed. What am I doing wrong?
XAML
<Page
x:Class="..."
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="..."
xmlns:helper="..."
xmlns:prop="..."
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Page.Resources>
<DataTemplate x:Key="Image" x:DataType="helper:ProductImage">
<Border BorderBrush="{x:Bind Path=Color, Mode=OneWay}" BorderThickness="1" Background="Transparent"
AllowDrop="True" Drop="Image_Drop" >
<Grid Width="{Binding ElementName=PIImageSize, Path=Value}"
Height="{Binding ElementName=PIImageSize, Path=Value}" >
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Margin="2" HorizontalAlignment="Center"
Text="{x:Bind Path=Type, Mode=OneWay}"
Foreground="{x:Bind Path=Color, Mode=OneWay}" />
<Image Grid.Row="1" Stretch="Uniform" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Source="{x:Bind Path=BitmapImage, Mode=OneWay}"/>
<TextBox Grid.Row="2" Text="{x:Bind Path=Path, Mode=TwoWay}" />
</Grid>
<Border.ContextFlyout>
</Border.ContextFlyout>
</Border>
</DataTemplate>
</Page.Resources>
...
</Page>
Code
private void Image_Drop(object sender, DragEventArgs e)
{
// Function is not executed
}
You also have to add the DragOver event, to accept the operation:
private void Image_DragOver(object sender, DragEventArgs e)
{
e.AcceptedOperation = Windows.ApplicationModel.DataTransfer.DataPackageOperation.Copy;
}

Xamarin Forms MVVM UWP ListView Binding doesn't work

I am trying to implement a MVVM ContentPage with a ListView that needs to bind to a populated generic list of XML model objects in a ViewModel but the binding fails. The code that is shown calls an API that does return a valid list of XML data. The same code works fine when the binding is done directly in the code behind of the XAML Xamarin contentpage by setting the ItemSource in the codebehind. As said, the problem only happens when trying to pass the ListView through the ViewModel assigned to the contentpage. I have stepped through the code in the ViewModel and the ListView is populated successfully but the binding just doesn't work. I have other controls that are on the page that the model binding does work for but the only control that doesn't work is the ListView. The code is shown below:
ViewModel:
using RestDemo.Model;
using RestDemo.Views;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using System.ComponentModel;
using System.Windows.Input;
using System.Collections.ObjectModel;
namespace RestDemo.ViewModel
{
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public ViewModel ()
{
GetRequest();
}
List<XmlPizzaDetails> _objPizzaList;
string _selectedDescription = "Descriptions: ";
bool _progress;
string _cusButtonText = "Hello";
public bool Progress
{
get { return _progress; }
set { _progress = value; }
}
public string CusButtonText
{
get { return _cusButtonText; }
set { _cusButtonText = value; }
}
public string SelectedDescription
{
get { return _selectedDescription; }
set { _selectedDescription = value; }
}
public List<XmlPizzaDetails> ObjPizzaList
{
get { return _objPizzaList; }
set
{
if (_objPizzaList != value)
{
_objPizzaList = value;
OnPropertyChanged("ObjPizzaList");
}
}
}
public string Description
{
get { return _selectedDescription; }
set { _selectedDescription = value; }
}
public ICommand SelectedCommand => new Command(() =>
{
CusButtonText = "Goodby";
});
event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged
{
add
{
}
remove
{
}
}
public async void GetRequest()
{
if (NetworkCheck.IsInternet())
{
Uri geturi = new Uri("http://api.androidhive.info/pizza/?format=xml"); //replace your xml url
HttpClient client = new HttpClient();
HttpResponseMessage responseGet = await client.GetAsync(geturi);
string response = await responseGet.Content.ReadAsStringAsync();
//Xml Parsing
ObjPizzaList = new List<XmlPizzaDetails>();
XDocument doc = XDocument.Parse(response);
foreach (var item in doc.Descendants("item"))
{
XmlPizzaDetails ObjPizzaItem = new XmlPizzaDetails();
ObjPizzaItem.ID = item.Element("id").Value.ToString();
ObjPizzaItem.Name = item.Element("name").Value.ToString();
ObjPizzaItem.Cost = item.Element("cost").Value.ToString();
ObjPizzaItem.Description = item.Element("description").Value.ToString();
ObjPizzaList.Add(ObjPizzaItem);
}
Progress = false;
}
}
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs(propertyName));
}
}
}
}
XAML
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:xlocal="clr-namespace:RestDemo.ViewModel"
xmlns:local="clr-namespace:RestDemo"
xmlns:Views="clr-namespace:RestDemo.Views"
x:Class="RestDemo.XmlParsingPageBehavior">
<ContentPage.BindingContext>
<xlocal:ViewModel />
</ContentPage.BindingContext>
<Grid>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Views:CustomButton Grid.Row="0" Grid.Column="0" Text="HOME" />
<Views:CustomButton Grid.Row="0" Grid.Column="1" Text="Administrative Maintence" />
<Views:CustomButton Grid.Row="0" Grid.Column="2" Text="User Maintence" />
<Views:CustomButton Grid.Row="0" Grid.Column="3" Text="About" />
</Grid>
<Grid Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Views:CustomButton Grid.Row="0" Grid.Column="0" Text="{Binding CusButtonText, Mode=TwoWay}">
<Views:CustomButton.Behaviors>
<local:ItemSelectedToCommandBehavior />
</Views:CustomButton.Behaviors>
</Views:CustomButton>
</Grid>
<Frame Margin="5, 5, 5, 5" Grid.Row="2" Grid.Column="1" BackgroundColor = "Cyan">
<ListView x:Name="PizzaListView" ItemsSource="{Binding ObjPizzaList}" Margin="5, 0, 5, 0" Grid.Row="2" Grid.Column="1" HorizontalOptions="FillAndExpand" HasUnevenRows="True">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid HorizontalOptions="FillAndExpand" Margin="0,0,0,0" Padding="20">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Label Text="{Binding Name}" HorizontalOptions="StartAndExpand" Grid.Row="0" TextColor="Blue" FontAttributes="Bold"/>
<Label Text="{Binding Cost}" HorizontalOptions="StartAndExpand" Grid.Row="1" TextColor="Orange" FontAttributes="Bold"/>
<Label Text="{Binding Description}" HorizontalOptions="StartAndExpand" Grid.Row="2" TextColor="Gray" FontAttributes="Bold"/>
<BoxView HeightRequest="2" Margin="0,10,10,0" BackgroundColor="Gray" Grid.Row="3" HorizontalOptions="Fill" />
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Frame>
</Grid>
<ActivityIndicator x:Name="ProgressLoader" IsVisible="{Binding Progress}" IsRunning="True"/>
</Grid>
</ContentPage>
I have it working. Yes ObservableCollections are the way to go but generic Lists are fine as well. The problem is that when the Model is bound the WebService call has not completed so when the List property is bound it is still null. Even when updated at this point the ObservableCollection won't work because it has not been seeded. The solution is to seed the ObservableCollection, or List, on the Page's OnAppearing event and bind the ViewModel as the BindingContext in this event. My solution is below:
protected override async void OnAppearing()
{
var vm = new ViewModel.ViewModel();
if (vm == null)
return;
HttpClient client = new HttpClient();
HttpResponseMessage responseGet = await client.GetAsync(vm.Geturi);
string response = await responseGet.Content.ReadAsStringAsync();
//Xml Parsing
var _objPizzaList = new ObservableCollection<XmlPizzaDetails>();
XDocument doc = XDocument.Parse(response);
vm.GetRequest(doc);
this.BindingContext = vm;
}

How can I format a DatePicker to display the date format day / month / year?

I'm using the Windows Phone 8.1 DatePicker
It's displaying the date as month/day/year by default and I can't see any way to change this to the 'correct' way of day/month/year.
This is how I declare the DatePicker
<DatePicker Name="datePicker" HorizontalAlignment="Center" MonthFormat="{}{month.full}"/>
displaying it as
I can see in the linked msdn article that I can use a DateTimeFormatter in conjunction with ComboBox selectors but that's not an option for me.
Is it possible?
To Edit the Template
In Xaml every control has a style which you can manipulate, to change it's look and feel. Controls also inherit from one another, for example a date picker is made up of a button and a content container. And a button is made up of a border and a content container.
To Update the date pickers style.. Right click on the date picker control in visual studio from the Menu click edit template then click edit a copy. For this example you want to edit the style of the button template with in the date picker Template...
You will also need to create a Converter class to used in the template
This answer worked for me
Page with date picker...
<Page
x:Class="DatePikerAnswer.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:DatePikerAnswer"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Page.Resources>
<!-- Format Converter -->
<local:DateConverter x:Key="FormatConverter"/>
<!-- My Button Style-->
<Thickness x:Key="PhoneBorderThickness">2.5</Thickness>
<FontWeight x:Key="PhoneButtonFontWeight">Semibold</FontWeight>
<x:Double x:Key="TextStyleLargeFontSize">18.14</x:Double>
<x:Double x:Key="PhoneButtonMinHeight">57.5</x:Double>
<x:Double x:Key="PhoneButtonMinWidth">109</x:Double>
<Thickness x:Key="PhoneTouchTargetOverhang">0,9.5</Thickness>
<SolidColorBrush x:Key="ButtonDisabledBackgroundThemeBrush" Color="Transparent"/>
<Style x:Key="MyButtonStyle" TargetType="Button">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderBrush" Value="{ThemeResource PhoneForegroundBrush}"/>
<Setter Property="Foreground" Value="{ThemeResource PhoneForegroundBrush}"/>
<Setter Property="BorderThickness" Value="{ThemeResource PhoneBorderThickness}"/>
<Setter Property="FontFamily" Value="{ThemeResource PhoneFontFamilyNormal}"/>
<Setter Property="FontWeight" Value="{ThemeResource PhoneButtonFontWeight}"/>
<Setter Property="FontSize" Value="{ThemeResource TextStyleLargeFontSize}"/>
<Setter Property="Padding" Value="9.5,0"/>
<Setter Property="MinHeight" Value="{ThemeResource PhoneButtonMinHeight}"/>
<Setter Property="MinWidth" Value="{ThemeResource PhoneButtonMinWidth}"/>
<Setter Property="HorizontalAlignment" Value="Left"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid x:Name="Grid" Background="Transparent">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualStateGroup.Transitions>
<VisualTransition From="Pressed" To="PointerOver">
<Storyboard>
<PointerUpThemeAnimation Storyboard.TargetName="Grid"/>
</Storyboard>
</VisualTransition>
<VisualTransition From="PointerOver" To="Normal">
<Storyboard>
<PointerUpThemeAnimation Storyboard.TargetName="Grid"/>
</Storyboard>
</VisualTransition>
<VisualTransition From="Pressed" To="Normal">
<Storyboard>
<PointerUpThemeAnimation Storyboard.TargetName="Grid"/>
</Storyboard>
</VisualTransition>
</VisualStateGroup.Transitions>
<VisualState x:Name="Normal"/>
<VisualState x:Name="PointerOver"/>
<VisualState x:Name="Pressed">
<Storyboard>
<PointerDownThemeAnimation Storyboard.TargetName="Grid"/>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentPresenter">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonPressedForegroundThemeBrush}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="Border">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonPressedBackgroundThemeBrush}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="Disabled">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentPresenter">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonDisabledForegroundThemeBrush}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="Border">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonDisabledBorderThemeBrush}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="Border">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonDisabledBackgroundThemeBrush}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Border x:Name="Border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Margin="{ThemeResource PhoneTouchTargetOverhang}">
<ContentPresenter x:Name="ContentPresenter"
AutomationProperties.AccessibilityView="Raw"
ContentTemplate="{TemplateBinding ContentTemplate}"
Content="{Binding Content, RelativeSource={RelativeSource TemplatedParent},Converter={StaticResource FormatConverter},ConverterParameter=\{0:dd/MM/yyyy\}}"
Foreground="{TemplateBinding Foreground}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
Margin="{TemplateBinding Padding}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Border>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!--DatePicker Style-->
<FontFamily x:Key="PhoneFontFamilyNormal">Segoe WP</FontFamily>
<x:Double x:Key="ContentControlFontSize">20.26</x:Double>
<Style x:Key="MyDatePickerStyle1" TargetType="DatePicker">
<Setter Property="FontFamily" Value="{ThemeResource PhoneFontFamilyNormal}"/>
<Setter Property="FontSize" Value="{ThemeResource ContentControlFontSize}"/>
<Setter Property="Foreground" Value="{ThemeResource DatePickerForegroundThemeBrush}"/>
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="HorizontalContentAlignment" Value="Left"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="DatePicker">
<StackPanel x:Name="LayoutRoot" Margin="{TemplateBinding Padding}">
<ContentPresenter x:Name="HeaderContentPresenter"
ContentTemplate="{TemplateBinding HeaderTemplate}"
Content="{TemplateBinding Header}" Margin="0,0,0,-3"
Style="{StaticResource HeaderContentPresenterStyle}"/>
<Button x:Name="FlyoutButton"
BorderBrush="{TemplateBinding Foreground}"
BorderThickness="2.5"
Background="{TemplateBinding Background}"
Foreground="{TemplateBinding Foreground}"
HorizontalAlignment="Stretch"
HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
IsEnabled="{TemplateBinding IsEnabled}"
Style="{StaticResource MyButtonStyle}"
Padding="6.5,0,0,3"/>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Page.Resources>
<Grid>
</Grid>
</Page>
Converter Class ...
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Data;
namespace DatePikerAnswer
{
class DateConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value != null)
{
///Convert Class throws exception so can not convert to date time
string TheCurrentDate = value.ToString();
string[] Values = TheCurrentDate.Split('/');
string Day, Month, Year;
Day = Values[1];
Month = Values[0];
Year = Values[2];
string retvalue = string.Format("{0}/{1}/{2}", Day, Month, Year);
return retvalue;
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
}
The End Result is ...
I needed to show Date as 'Month Year', I tried some solutions I thought about but they didn't work , searched a little and finally found this question and the answer by StuartSmith.
Based on his answer I came up with similar solution that works around localization issue mentioned in comment by Kubaskista
#StuartSmith It will not work for German localization and probably some other regions due to different data format. btw: any idea why "value" in converter is not possible to convert into DateTime?
1- Define Date Picker in xaml, give it name "FirstDatePicker" and then from Designer edit template then choose edit a copy.
<DatePicker x:Name="FirstDatePicker" VerticalAlignment="Top" Grid.Row="1" Margin="0,12,0,0" CalendarIdentifier="GregorianCalendar" DayVisible="False" Padding="0" Style="{StaticResource DatePickerStyle}" RequestedTheme="Light"/>
2- Right Click on FlyoutButton -> Additional Templates -> Edit Generated Content -> Edit a copy.
3- Inside content template, We will bind directly to Date property of FirstDatePicker and by using of StringFormatConverter you can format the date as you wish and override culture also.
<DataTemplate x:Key="DateFormatTemplate">
<Grid>
<TextBlock x:Name="textBlock" HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding Date, ConverterParameter=MMMM yyyy, Converter={StaticResource DateFormatConverter}, ElementName=FirstDatePicker, Mode=OneWay}" VerticalAlignment="Top"/>
</Grid>
</DataTemplate>
4- Add StringFormatConverter to solution, Don't forget to add it to resources section of page.
public class DateFormatConverter : IValueConverter
{
#region IValueConverter Members
public object Convert ( object value, Type targetType, object parameter, string language )
{
if(!(value is DateTime || value is DateTimeOffset) || parameter == null) return value;
if(value is DateTime)
{
var date = (DateTime)value;
return date.ToString(parameter.ToString(), CultureInfo.CurrentCulture);
}
else
{
var date = (DateTimeOffset)value;
return date.ToString(parameter.ToString(), CultureInfo.CurrentCulture);
}
}
public object ConvertBack ( object value, Type targetType, object parameter, string language )
{
throw new NotImplementedException();
}
#endregion
}
Note:You can change 'CultureInfo.CurrentCulture' to new Culture("ar-EG") as example or use language passed in converter.
Finally, Here is what i have in resources section of page
<converters:DateFormatConverter x:Key="DateFormatConverter"/>
<x:Double x:Key="ContentControlFontSize">20.26</x:Double>
<FontWeight x:Key="PhoneButtonFontWeight2">Semibold</FontWeight>
<DataTemplate x:Key="DateFormatTemplate">
<Grid>
<TextBlock x:Name="textBlock" HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding Date, ConverterParameter=MMMM yyyy, Converter={StaticResource DateFormatConverter}, ElementName=FirstDatePicker, Mode=OneWay}" VerticalAlignment="Top"/>
</Grid>
</DataTemplate>
<Style x:Key="DatePickerStyle" TargetType="DatePicker">
<Setter Property="FontFamily" Value="{ThemeResource PhoneFontFamilyNormal}"/>
<Setter Property="FontSize" Value="{ThemeResource ContentControlFontSize}"/>
<Setter Property="Foreground" Value="{ThemeResource DatePickerForegroundThemeBrush}"/>
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="HorizontalContentAlignment" Value="Left"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="DatePicker">
<StackPanel x:Name="LayoutRoot" Margin="{TemplateBinding Padding}">
<ContentPresenter x:Name="HeaderContentPresenter" ContentTemplate="{TemplateBinding HeaderTemplate}" Content="{TemplateBinding Header}" Margin="0,0,0,-3" Style="{StaticResource HeaderContentPresenterStyle}"/>
<Button x:Name="FlyoutButton" BorderBrush="{TemplateBinding Foreground}" BorderThickness="2.5" Background="{TemplateBinding Background}" Foreground="{TemplateBinding Foreground}" HorizontalAlignment="Stretch" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" IsEnabled="{TemplateBinding IsEnabled}" Padding="12,10" Margin="0" ContentTemplate="{StaticResource DateFormatTemplate}"/>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

Binding Collectionviewsource with WPF Datagrid and Entity Framework

I'm relatively new at WPF and C#. Following this example, I have created a form with a datagrid and two comboboxes (FileName and PartID) that I'd like to use to filter the datagrid (surveyresponsesDataGrid).
Here is my XAML for the WPF Form:
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:dat="clr-namespace:System.Windows.Data;assembly=PresentationFramework"
Title="Review Data" Height="446" Width="987" mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:my="clr-namespace:SWA_IFR" Loaded="Window_Loaded">
<Window.Resources>
<CollectionViewSource
Source="{Binding ElementName=surveyresponses, Path=FileName.SelectedItem}"
x:Key="cvs" Filter="fn_Filter"
x:Name="srView"
CollectionViewType="{x:Type dat:ListCollectionView}" />
</Window.Resources>
<Grid>
<DataGrid AutoGenerateColumns="False" EnableRowVirtualization="True" Height="247" HorizontalAlignment="Left"
ItemsSource="{Binding Source={StaticResource cvs}}" Margin="12,93,0,0" Name="surveyresponsesDataGrid"
RowDetailsVisibilityMode="VisibleWhenSelected" VerticalAlignment="Top" Width="941">
<DataGrid.Columns>
<DataGridTextColumn x:Name="fileUploadNameColumn" Binding="{Binding Path=FileUploadName}" Header="File Upload Name" Width="*" />
<DataGridTextColumn x:Name="participantIDColumn" Binding="{Binding Path=ParticipantID}" Header="Participant ID" Width="*" />
<DataGridTextColumn x:Name="quesIDColumn" Binding="{Binding Path=QuesID}" Header="Ques ID" Width="*" />
<DataGridTextColumn x:Name="quesTypeColumn" Binding="{Binding Path=QuesType}" Header="Ques Type" Width="*" />
<DataGridTextColumn x:Name="scoreIntColumn" Binding="{Binding Path=ScoreInt}" Header="Score Int" Width="*" />
<DataGridTextColumn x:Name="scoreTextColumn" Binding="{Binding Path=ScoreText}" Header="Score Text" Width="*" />
<DataGridTextColumn x:Name="scoreDescrColumn" Binding="{Binding Path=ScoreDescr}" Header="Score Descr" Width="*" />
</DataGrid.Columns>
</DataGrid>
<ComboBox Height="29" HorizontalAlignment="Left" Margin="184,17,0,0" Name="FileName" VerticalAlignment="Top" Width="211" SelectionChanged="FileName_SelectionChanged" />
<Label Content="Filter by File Upload Name" Height="29" HorizontalAlignment="Left" Margin="14,17,0,0" Name="label2" VerticalAlignment="Top" Width="159" />
<ComboBox Height="29" HorizontalAlignment="Left" Margin="184,52,0,0" Name="PartID" VerticalAlignment="Top" Width="211" />
<Label Content="Filter by Participant ID" Height="29" HorizontalAlignment="Left" Margin="14,52,0,0" Name="label1" VerticalAlignment="Top" Width="159" />
</Grid>
Here is my code:
public partial class ReviewData : Window
{
SMEntities context = new SMEntities();
public ReviewData()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var filename = context.surveyresponses.Select(f => f.FileUploadName).Distinct();
this.FileName.ItemsSource = filename;
var partid = context.surveyresponses.Select(p => p.ParticipantID).Distinct();
this.PartID.ItemsSource = partid;
}
void fn_Filter(object sender, FilterEventArgs e)
{
if (e.Item is surveyresponse)
e.Accepted = (e.Item as surveyresponse).FileUploadName.ToUpper().Contains(FileName.Text.ToUpper());
else
e.Accepted = true;
}
private void RefreshList()
{
if (surveyresponsesDataGrid.Items is CollectionView)
{
CollectionViewSource csv = (CollectionViewSource)FindResource("cvs");
if (csv != null)
csv.View.Refresh();
}
}
private void srFilter_TextChanged(object sender, TextChangedEventArgs e)
{
RefreshList();
}
} }
First problem is that I don't think the CollectionViewSource is correctly setup in the Window.Resource section, but I can't find any clear guidance about what's off. The EF class is surveyresponses but not sure that the I've correctly set the Path attribute -- currently it is set to the SelectedItem of the first combobox FileName. My goal is to filter the datagrid for only the entries that match the selection in the FileName combobox.
Second problem is that I'm uncertain how I would go about having a secondary filter, such that once the first filter is set, that selecting the PartId combobox will further filter the datagrid based on the second field (Participant ID).
I'm missing something fundamental and don't see what it is.
Thanks for the guidance.

WPF/C#: 'Slide to Unlock' feature from iPhone

I just want to ask for your opinion on how to achieve the 'Slide to Unlock' feature from iPhone using Windows Presentation Foundation.
I already came across to this article: iPhone slide to unlock progress bar (part 1), and wondering if you can give me some other resources for a good head start. Thank you.
I would retemplate a Slider, as this is the closest control, functionality-wise.
You should catch the event of Value_Changed, and if Value == Maximum then the slider is "opened".
Retemplating the control would make it look like your "unlock control" with ease. I'll paste later an example.
-- EDIT --
Have free time at work, so I started it for you.
The usage is as follows:
<Grid x:Name="LayoutRoot">
<Slider Margin="185,193,145,199" Style="{DynamicResource SliderStyle1}"/>
</Grid>
and the ResourceDictionary:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d">
<LinearGradientBrush x:Key="MouseOverBrush" EndPoint="0,1" StartPoint="0,0">
<GradientStop Color="#FFF" Offset="0.0"/>
<GradientStop Color="#AAA" Offset="1.0"/>
</LinearGradientBrush>
<LinearGradientBrush x:Key="LightBrush" EndPoint="0,1" StartPoint="0,0">
<GradientStop Color="#FFF" Offset="0.0"/>
<GradientStop Color="#EEE" Offset="1.0"/>
</LinearGradientBrush>
<LinearGradientBrush x:Key="NormalBorderBrush" EndPoint="0,1" StartPoint="0,0">
<GradientStop Color="#CCC" Offset="0.0"/>
<GradientStop Color="#444" Offset="1.0"/>
</LinearGradientBrush>
<Style x:Key="SimpleScrollRepeatButtonStyle" d:IsControlPart="True" TargetType="{x:Type RepeatButton}">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderBrush" Value="Transparent"/>
<Setter Property="IsTabStop" Value="false"/>
<Setter Property="Focusable" Value="false"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type RepeatButton}">
<Grid>
<Rectangle Fill="{TemplateBinding Background}" Stroke="{TemplateBinding BorderBrush}" StrokeThickness="{TemplateBinding BorderThickness}"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="ThumbStyle1" d:IsControlPart="True" TargetType="{x:Type Thumb}">
<Setter Property="SnapsToDevicePixels" Value="true"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Thumb}">
<Grid Width="54">
<Ellipse x:Name="Ellipse" />
<Border CornerRadius="10" >
<Border.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FFFBFBFB" Offset="0.075"/>
<GradientStop Color="Gainsboro" Offset="0.491"/>
<GradientStop Color="#FFCECECE" Offset="0.509"/>
<GradientStop Color="#FFA6A6A6" Offset="0.943"/>
</LinearGradientBrush>
</Border.Background>
</Border>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Fill" Value="{StaticResource MouseOverBrush}" TargetName="Ellipse"/>
</Trigger>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Fill" Value="{StaticResource DisabledBackgroundBrush}" TargetName="Ellipse"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="SliderStyle1" TargetType="{x:Type Slider}">
<Setter Property="Background" Value="{StaticResource LightBrush}"/>
<Setter Property="BorderBrush" Value="{StaticResource NormalBorderBrush}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Slider}">
<Border CornerRadius="14" Padding="4">
<Border.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF252525" Offset="0"/>
<GradientStop Color="#FF5C5C5C" Offset="1"/>
</LinearGradientBrush>
</Border.Background>
<Grid x:Name="GridRoot">
<TextBlock Text="Slide to unlock" HorizontalAlignment="Center" VerticalAlignment="Center" />
<!-- TickBar shows the ticks for Slider -->
<!-- The Track lays out the repeat buttons and thumb -->
<Track x:Name="PART_Track" Height="Auto">
<Track.Thumb>
<Thumb Style="{StaticResource ThumbStyle1}"/>
</Track.Thumb>
<Track.IncreaseRepeatButton>
<RepeatButton Style="{StaticResource SimpleScrollRepeatButtonStyle}" Command="Slider.IncreaseLarge" Background="Transparent"/>
</Track.IncreaseRepeatButton>
<Track.DecreaseRepeatButton>
<RepeatButton Style="{StaticResource SimpleScrollRepeatButtonStyle}" Command="Slider.DecreaseLarge" d:IsHidden="True"/>
</Track.DecreaseRepeatButton>
</Track>
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="TickPlacement" Value="TopLeft"/>
<Trigger Property="TickPlacement" Value="BottomRight"/>
<Trigger Property="TickPlacement" Value="Both"/>
<Trigger Property="IsEnabled" Value="false"/>
<!-- Use a rotation to create a Vertical Slider form the default Horizontal -->
<Trigger Property="Orientation" Value="Vertical">
<Setter Property="LayoutTransform" TargetName="GridRoot">
<Setter.Value>
<RotateTransform Angle="-90"/>
</Setter.Value>
</Setter>
<!-- Track rotates itself based on orientation so need to force it back -->
<Setter TargetName="PART_Track" Property="Orientation" Value="Horizontal"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
Note that this is a very good start, but it's not everything.
I would also define a custom control that derives from slider and that uses this style automatically. Also I would expose a SlideUnlocked event when the user slides all the way right.
To finish it all i would also add an animation that moves the Thumb back left in case the user has dragged it right, but not all the way (to imitate iPhone's UX exactly.)
Good luck, and ask away if you don't know how to implement any of the stages i suggested.
WPF slider has got one "-" and it is value ,
always when you move it, value is for example in decimal 1,122213174 so one "-".
But another way to create slider is in Windows forms.
Create trackBar1 ,and maximum = 100 points.
This is for Windows forms application:
On trackBar1_mouse_up:
if(trackBar1.Value < 100)
{
//Animation - slide back dynamicaly.
for(int i=0;i<=trackBar1.Value;i++){
int secondVal=trackBar1.Value-i;
trackBar1.Value=secondVal;
System.Threading.Thread.Sleep(15);
}
}
if(trackBar1.Value==100)
{
//sets enabled to false, then after load cannot move it.
trackBar1.Enabled=false;
MessageBox.Show("Done!");
}
And this for WPF Slider: (on PreviewMouseUp)
if (Convert.ToInt16(slider1.Value) < 99)
{
//Animation - slide back dynamicaly.
for (int i = 0; i < Convert.ToInt16(slider1.Value); i++)
{
int secondVal = Convert.ToInt32(slider1.Value) - i;
slider1.Value = secondVal;
System.Threading.Thread.Sleep(10);
if (secondVal < 2)
{
slider1.Value = 0;
}
}
}
if (Convert.ToInt16(slider1.Value) > 99)
{
//sets enabled to false, then after load cannot move it.
slider1.IsEnabled = false;
slider1.Value = 100;
MessageBox.Show("Done!");
}
Good luck! I hope it helps, try it with slider, but I think application will crash.