Pages

Showing posts with label Data Binding. Show all posts
Showing posts with label Data Binding. Show all posts

Saturday, 3 March 2012

DataType instead of DataTemplateSelector

Nearly three years ago I posted about the use of the DataTemplateSelector.
It transpires that because I was using different types of objects in my ItemsSource I could have used the DataType attribute of the DataTemplate.
Define the DataTemplates in the usual way but add the DataType attribute.
      <DataTemplate DataType="{x:Type dts:BookingLineItem}">
      <DataTemplate DataType="{x:Type dts:CCardPaymentLineItem}">
      <DataTemplate DataType="{x:Type dts:CashPaymentLineItem}">
      <DataTemplate DataType="{x:Type dts:LineItem}">
There is no need to define the DataTemplateSelector in the resources, no C# class to write and the ListBox becomes simpler:
      <ListBox Name="theSecondTillRoll"
               Height="150"
               Width="330"
               ItemsSource="{Binding SaleItems}" />
The DataTemplateSelector project is on GoogleCode and demonstrates both techniques.

Friday, 2 March 2012

WPF String Formatting

There are a number of ways to use formatted strings and we seem to use nearly all of them in our application. Because the format of the formatting string varies slightly I thought I'd document the different techniques.
Firstly we need some simple properties for the XAML Bindings. Notice that the ToString version needs neither the index (0:) or the curly braces.
public partial class MainWindow : Window
{
   public String FormattedDate
   {
      get { return String.Format("{0:dd MMM yyy}", DateTime.Now); }
   }
   public String DateToString
   {
      get { return DateTime.Now.ToString("dd MMM yyy"); }
   }
   public DateTime RawDateTime
   {
      get { return DateTime.Now; }
   }
   public MainWindow()
   {
      InitializeComponent();
      DataContext = this;
   }
}
The first two TextBlocks bind directly to the pre-formatted properties.
      <TextBlock Text="{Binding FormattedDate}" />
      <TextBlock Text="{Binding DateToString}" />
Or we can bind to the raw data and use StringFormat. We can escape the curly braces in a couple of ways.
      <TextBlock Text="{Binding Path=RawDateTime, StringFormat=\{0:dd MMM yyyy\}}" />
      <TextBlock Text="{Binding Path=RawDateTime, StringFormat={}{0:dd MMM yyyy}}" />
The leading curly braces in the second version can be replaced by constant text that is rendered as part of the formatted string. But it seems a bit "sensitive" so I don't use it.
      <TextBlock Text="{Binding Path=RawDateTime, StringFormat=Today is {0:dd MMM yyyy}}" />
Next up is a Converter for which we need an IValueConverter class:
class DateConverter : IValueConverter
{
   public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
   {
      if (value is DateTime)
      {
         return ((DateTime)value).ToString("dd MMM yyy");
      }
      return value;
   }

   public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
   {
      throw new NotImplementedException();
   }
}
And the corresponding XAML to use the Converter:
        xmlns:local="clr-namespace:WpfWaltz"
...
   <Window.Resources>
      <local:DateConverter x:Key="dateConverter"; />
   </Window.Resources>
...
      <TextBlock Text="{Binding Path=RawDateTime, Converter={StaticResource dateConverter}}" />
Finally, I had assumed that the indexer in the StringFormat was just a necessary evil since it was always 0: and hadn't considered using StringFormat with a MultiBinding like this:
      <TextBlock>
         <TextBlock.Text>
            <MultiBinding StringFormat="{}{0:dd MMM yyyy} {1:hh:mm:ss}">
               <Binding Path="RawDateTime" /> 
               <Binding Path="RawDateTime" />
            </MultiBinding>
         </TextBlock.Text>
      </TextBlock>
The StringFormatting project that has all the code can be downloaded from GoogleCode.

Saturday, 25 February 2012

Datagrid loading message and VisualBrush

I have to load a DataGrid from a slow running DB query. To keep the UI responsive I'm running the data retrieval on a worker thread but I wanted an inobtrusive message to be displayed to the User during the loading phase. I replaced the DataGrid's Background with a TextBlock contained in VisualBrush. With the TextBlock's Text and Visibility bound to the underlying ViewModel. For those cases where there is no data to be shown in the DataGrid I show an alternate message.
<DataGrid ItemsSource="{Binding Source{StaticResource ViewModel},Path=EnrolledStudents}"
            CanUserAddRows="False"
            CanUserDeleteRows="False"
            AutoGenerateColumns="False"
            IsReadOnly="True">
   <DataGrid.Background>
      <VisualBrush Stretch="None">
         <VisualBrush.Visual>
            <StackPanel Background="White">
               <TextBlock HorizontalAlignment="Center"
                           VerticalAlignment="Center"
                           FontSize="10pt"
                           Margin="2"
                           Foreground="Red"
                           Text="{Binding Path=Strings.V_LabelLoading}"
                           Visibility="{Binding Source{StaticResource ViewModel}, Path=EnrolledStudentLoadingInProgress, Converter={StaticResource boolToCollapsedVisibilityConverter}}" />
               <TextBlock HorizontalAlignment="Center"
                           VerticalAlignment="Center"
                           FontSize="10pt"
                           Margin="2"
                           Foreground="Silver"
                           Text="{Binding Path=Strings.V_LabelNoEnrolledStudents}"
                           Visibility="{Binding Source{StaticResource ViewModel}, Path=NoEnrolledStudents, Converter={StaticResource boolToCollapsedVisibilityConverter}}" />
            </StackPanel>
         </VisualBrush.Visual>
      </VisualBrush>
   </DataGrid.Background>
   <DataGrid.Columns>

Monday, 10 January 2011

ResourceStrings in XAML

I needed to replace some hard-coded text in the xaml templates used in our Till Roll control. There was no easy route through to a general ViewModel that could expose some relevant properties to bind to.
In the end I chose to bind directly to the ResourceStrings resource using an x:Static
...
xmlns:local="clr-namespace:Sandstorm.PointOfSale.Modules.Tender.Resources"
...
<TextBlock Padding="20,0,0,0" Text="{Binding Source={x:Static local:ResourceStrings.V_Discount}, Mode=OneTime}" FontStyle="Italic"/>

Tuesday, 28 September 2010

UpdateSourceTrigger in DataGrid

Inside a DataGrid, any control you add into a TemplateColumn which is bound TwoWay, used to use its default value of UpdateSourceTrigger, but the .NET 4 version of DataGrid overrides this by default to be Explicit.

For example:
<DataGrid>
<DataGrid.Columns>
<DataGrid.TemplateColumn>
<DataTemplate>
<TextBox Text={Binding MyProperty} />
</.....>

This used to work just fine.. When the value in TextBox changed, it would update MyProperty when the textbox lost focus (this is the default value for a textbox of UpdateSourceTrigger).
This no longer happens.
We now need to explicitly set the UpdateSourceTrigger for all UI controls inside a DataGrid Template column which should be updating their underlying property store.

Now becomes:
    <TextBox   Text={Binding MyProperty, UpdateSourceTrigger=LostFocus} />

Wednesday, 2 June 2010

Debugging Bindings

I just want to keep track of this page to remind me how to get more information about a binding when debugging binding issues.

PresentationTraceSources.TraceLevel

Wednesday, 15 July 2009

Databinding and Nullable Types

In this article (Using WPF Binding StringFormat property with nullable types) Karl Shifflett describes how to bind to properties that have a nullable type.

In summary, use TargetNullValue property of the binding like this:
<TextBox
Text="{Binding Path=NumberOfComputers,
TargetNullValue={x:Static sys:String.Empty},
StringFormat=\{0:D\}}" />

TargetNullValue requires .NET 3.5 Framework Service Pack 1. Previously this would have required a IValueConverter class to deal with the Null values.

Tuesday, 14 July 2009

Parameter Ordering

Although the two ComboBox samples below look very similar they actually function a little differently.
The first sample sets the selected item based on the SelectedItem binding and then almost instantaneously sets the SelectedItem based on the first record in the ItemsSource binding.
<ComboBox
DisplayMemberPath="Description"
SelectedItem="{Binding Path=EditedCourse.Centre, Mode=TwoWay}"
SSForm:FormItem.LabelContent="Centre"
IsEditable="{Binding Path=EditedCourse.IsCentreEditable}">
<ComboBox.ItemsSource>
<Binding
Mode="OneWay">
<Binding.Source>
<CollectionViewSource
x:Name="PART_CentresView"
Source="{Binding Source={StaticResource ViewModel}, Path=Centres, Mode=OneWay}" />
</Binding.Source>
</Binding>
</ComboBox.ItemsSource>
</ComboBox>

The second sample sets the selected item based on the SelectedItem binding only and therefore does what I would have expected to happen from the first sample.
<ComboBox
DisplayMemberPath="Description"
SSForm:FormItem.LabelContent="Centre"
IsEditable="{Binding Path=EditedCourse.IsCentreEditable}">
<ComboBox.ItemsSource>
<Binding
Mode="OneWay">
<Binding.Source>
<CollectionViewSource
x:Name="PART_CentresView"
Source="{Binding Source={StaticResource ViewModel}, Path=Centres, Mode=OneWay}" />
</Binding.Source>
</Binding>
</ComboBox.ItemsSource>
<ComboBox.SelectedItem>
<Binding
Path="EditedCourse.Centre"
Mode="TwoWay" />
</ComboBox.SelectedItem>

</ComboBox>

The implication is that the selected item is not necessarily what you would expect it to be.

In the first sample, the final selected item is the first (default) entry in the item source collection, and in the second sample the final selected item is the item bound to in the SelectedItem property.

Monday, 6 April 2009

DataTemplateSelector

UPDATE: There is an alternate technique described here and example code available from GoogleCode.

On our till roll I want to display each different category of product using a specific DataTemplate.

We start by defining the DataTemplates to be used in the usual way:

<DataTemplate x:Key="listBookingTemplate">...
<DataTemplate x:Key="listCCardTemplate">...
<DataTemplate x:Key="listCashTemplate">...
<DataTemplate x:Key="listDefaultTemplate">...

Then the DataTemplateSelector which is the link between the xaml DataTemplates and the C# class (TillRollTemplateSelector) that determines which template to use:

<ss:TillRollTemplateSelector 
 BookingTemplate="{StaticResource listBookingTemplate}" 
 CCardTemplate="{StaticResource listCCardTemplate}"
 CashTemplate="{StaticResource listCashTemplate}"  
 DefaultTemplate="{StaticResource listDefaultTemplate}" 
 x:Key="tillTemplateSelector" />

Then we need to wire up the template selector resource (tillTemplateSelector) to the ListBox that will display the data:

<ListBox Name="theTillRoll" Height="250" Width="330"
 ItemsSource="{Binding Source={StaticResource ViewModel}, Path=SaleItems}" 
 ItemTemplateSelector="{StaticResource tillTemplateSelector}"
 />

Finally, we define the C# class:

public class TillRollTemplateSelector : DataTemplateSelector
{
public DataTemplate BookingTemplate { get; set; }
public DataTemplate CashTemplate { get; set; }
public DataTemplate CCardTemplate { get; set; }
public DataTemplate DefaultTemplate { get; set; }
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
if (item is BookingLineItem) return BookingTemplate;
if (item is CashPaymentLineItem) return CashTemplate;
if (item is CCardPaymentLineItem) return CCardTemplate;
return DefaultTemplate;
}
}

The object item passed to the SelectTemplate method is of the same type as bound to the ListBox via the ItemsSource.

MultiBinding

I wanted to control the IsEnabled property of a Button based on the properties of two other controls.
Specifically I wanted to only enable the LogIn button if both the Site combobox and UserName textbox had a value available.

I created a MultiBinding for the Button like this:
<Button.IsEnabled>
   <MultiBinding Converter="{StaticResource loginConverter}">
      <Binding ElementName="xSite" Path="SelectedIndex"/>
      <Binding ElementName="xUsername" Path="Text"/>
   </MultiBinding>
</Button.IsEnabled>

And a IMultiValueConverter like this:
public class LoginConverter : IMultiValueConverter
{
   public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
   {
      // SelectedIndex of the ComboBox
      int selectedIndex = (int)values[0];
 
      // Length of Text in TextBox
      int selectedLength = ((string)values[1]).Length;
 
      // Only enable Button if both Combo and TextBox have data
      if (selectedIndex == -1 || selectedLength==0)
      {
         return false;
      }
      else
      {
         return true;
      }
   }
   public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
   {
      throw new NotImplementedException();
   }
}

The array of object[] values are presented in the same order as the Bindings within the MultiBinding.

Finally here is an example of using MultiBinding with StringFormat.

Friday, 13 March 2009

Forcing OnPropertyChanged to update the UI

Having used my new Func<T, T> friend (see Action<T> and Func<T, TResult>) the bound TextBox refused to show the revised value. Even though OnPropertyChanged("...") had been called the property's "getter" was not called by WPF.

I don't really understand why.

To get round this problem I added a FormattingConverter to the TextBox called DoNothingConverter. Its presence is sufficient to ensure the UI updates.

public class DoNothingConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value;
}
}

Sunday, 1 February 2009

Validation in MVVM

We're following the MVVM pattern and using Josh Smith's example app Using a Viewmodel to provide meaningful Validation Error Messages to implement validation.

When I was in debugger I noticed that some code was executing twice so I traced through the code once the focus left the textbox.

The order of processing was:
[External Code]
ViewModel.Property.Set
OnPropertyChanged
[External Code]
ViewModel.this[propertyName]
But when you add in a FormattingConverter the order becomes:
[External Code]
FormattingConverter.ConvertBack
[External Code]
ViewModel.Property.Set
OnPropertyChanged
[External Code]
ViewModel.Property.Get
[External Code]
FormattingConverter.Convert
[External Code]
ViewModel.this[propertyName]
[External Code]
ViewModel.this[propertyName]
Which means that the validation gets fired twice.

Because we don't want invalid data in our Model we've recently moved the setting of the Model.Property into the ModelView.this[propertyName] method - not ideal but it is the last opportunity where we still have control. Of course the "double-validation" results in the Model.Property being set twice. Not usually a problem but I fear some hidden side-effect somewhere down the line.

Another slight aggravation is that the Convert function is called before the validation and therefore invalid data will fail to convert then we'll attempt the conversion in the validation process (which was the whole point of this exercise).

Wednesday, 26 November 2008

INotifyPropertyChanged

I had a conversation with Martin about INotifyPropertyChanged and it made me realise there was an (other) aspect of Binding that I hadn't appreciated.

So I created a little project to test my assumptions.

1) Business Class implements INotifyPropertyChanged

public class Person : INotifyPropertyChanged
{
private string _surname = "";
public string Surname
{
get { return _surname; }
set
{
_surname = value;
OnPropertyChanged("Surname");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
2) Model exposing two instances of Person. Model does not implement INPC

public class Model
{
public Person APerson { get; set; }
public Person AnotherPerson { get; set; }
public Model()
{
APerson = new Person();
AnotherPerson = new Person();
}
}
3) Bind to only one of the two instances of Person in the Model

<TextBlock Text="{Binding Model.APerson.Surname}"></TextBlock>
<Button Click="Button_Click">Go</Button>
4) Wire it all up

public partial class Window2 : Window
{
private Model _model = new Model();
public Model Model
{
get { return _model; }
set { _model = value; }
}
public Window2()
{
InitializeComponent();
DataContext = this;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Model.APerson.Surname = "Smith";
Model.AnotherPerson.Surname = "Jones";
}
}
Result:
PropertyChanged is only hooked up for APerson and not for AnotherPerson because nothing is bound to AnotherPerson in the xaml.

Conclusion:
I might need to revisit the changes I made to AbstractModel hooking up PropertyChanged and DataError. Currently they are hooked up when the Model is instantiated, regardless of whether there is any binding in the xaml.

Tuesday, 18 November 2008

MultiBinding

I stumbled across MultiBinding today. I have no immediate use for it but I mustn't forget that it is available.

There is a nice simple example from MSDN here: MultiBinding Class

Saturday, 25 October 2008

Memory Usage

The Sandstorm client app is currently using about 83mb of RAM at runtime. It also consumes up to 25% of CPU time when idle. When the app is minimised the CPU usage drops to 0%. The CPU usage is regardless of whether Sandstorm is being run from within the VS2008 IDE.

I ran a little test app and its RAM footprint topped out at 39mb when run inside the VS2008 IDE. Running as a standalone exe it used a more "modest" 23mb. Interestingly it used no CPU time when idle.

Finding memory leaks in WPF based applications

Avoiding WPF Memory leak with Databinding

A memory leak may occur when you use data binding in Windows Presentation Foundation

Martin and I concluded that we need to implement INotifyPropertyChanged on any class that will be involved in Databinding. The most likely route will be to derive all the relevant classes from a base class that implements INPC.

This tool has a "visual profiler" which shows a graph of CPU usage.

WPF Performance Tool

Sunday, 5 October 2008

WPF ComboBox Data Binding

Binding a enum property (PaymentFrequency) to a WPF ComboBox.
This property provides the ItemsSource for the combobox by building a dictionary of enum (key) and enum.ToString (value).
   public enum PaymentFrequency
   {
      DayOfPlay,
      Monthly,
      None,
      Quarterly,
      Weekly,
   }
Expose this as a Property and Dictionary for Binding purposes:
      public PaymentFrequency Frequency { get; set; }

      public IDictionary<PaymentFrequency, string> FrequencyList
      {
         get
         {
            IDictionary<PaymentFrequency, string> frequencyList = new Dictionary<PaymentFrequency, string>();
            foreach (PaymentFrequency pf in Enum.GetValues(typeof(PaymentFrequency)))
            {
               frequencyList.Add(pf, pf.ToString());
            }
            return frequencyList;
         }
      }
The corresponding xaml (not forgetting the UpdateSourceTrigger=PropertyChanged if the ComboBox is inside a DataGrid as discussed here):
      <ComboBox ItemsSource="{Binding Path=FrequencyList, Mode=OneTime}"
                SelectedValuePath="Key"
                DisplayMemberPath="Value"
                SelectedValue="{Binding Path=Frequency, UpdateSourceTrigger=PropertyChanged}">
      </ComboBox>
For Internationalisation purposes it would be better to use Resource Strings to provide the descriptions for the combobox. I used a prefix of "PF_" on all the strings to ensure they are unique:

PF_DayOfPlay Day of Play 
PF_Monthly Monthly 
PF_None  None 
PF_Quarterly Quarterly 
PF_Weekly Weekly
Then modify the FrequencyList getter:
      public PaymentFrequency Frequency { get; set; }

      public IDictionary<PaymentFrequency, string> FrequencyList
      {
         get
         {
            IDictionary<PaymentFrequency, string> frequencyList = new Dictionary<PaymentFrequency, string>();
            foreach (PaymentFrequency pf in Enum.GetValues(typeof(PaymentFrequency)))
            {
               frequencyList.Add(pf, ResourceStrings.ResourceManager.GetString("PF_" + pf.ToString()));
            }
            return frequencyList;
         }
      }
A final tweak is to sort the descriptions displayed in the combobox into alphabetic order based on the translated strings.
      public PaymentFrequency Frequency { get; set; }

      public IDictionary<PaymentFrequency, string> FrequencyList
      {
         get
         {
            IDictionary<PaymentFrequency, string> frequencyList = new Dictionary<PaymentFrequency, string>();
            foreach (PaymentFrequency pf in Enum.GetValues(typeof(PaymentFrequency)))
            {
               frequencyList.Add(pf, ResourceStrings.ResourceManager.GetString("PF_" + pf.ToString()));
            }
            return frequencyList.OrderBy(f => f.Value).ToDictionary(f => f.Key, f => f.Value);
         }
      }
The ComboboxDataBinding example project includes this code and can be downloaded from GoogleCode.