Sladescross's Blog

Blogging about Sharepoint related stuff

WPF Dispatcher and Threading Architecture September 13, 2012

Filed under: Dispatcher,Threading,WPF — sladescross @ 3:04 pm

Typically, WPF applications start with two threads: one for handling rendering and another for managing the UI. The rendering thread effectively runs hidden in the background while the UI thread receives input, handles events, paints the screen, and runs application code. Most applications use a single UI thread, although in some situations it is best to use several. We’ll discuss this with an example later.

The UI thread queues work items inside an object called a Dispatcher. The Dispatcher selects work items on a priority basis and runs each one to completion.  Every UI thread must have at least one Dispatcher, and each Dispatcher can execute work items in exactly one thread.

The trick to building responsive, user-friendly applications is to maximize the Dispatcher throughput by keeping the work items small. This way items never get stale sitting in the Dispatcher queue waiting for processing. Any perceivable delay between input and response can frustrate a user.


WPF Binding and Value Converters and Binding Paths June 10, 2012

Filed under: ancestor,Binding,source,target,value converter,WPF — sladescross @ 1:59 pm
This is an example of data binding where your source is the slider’s Value and the target is your label control’s Content property. In this scenario, the mapping between your slider’s position and the value displayed on your label is pretty straightforward and a built-in converter takes care of displaying the right values.

In numerous scenarios, though, such a a direct mapping between your data does not exist. The built-in converter simply will not know what to do. In this tutorial, you will see one such example where you are taking RGB values from the Adobe Kuler recent themes and setting it equal to the background of your window.

The color value returned by Adobe Kuler is in a form such as FFFFFF. The format WPF brushes use for displaying colors is #FFFFFF. The difference is in the # symbol that WPF seeks but which our data source from the Kuler feed does not provide. Reconciling this difference is where value converters come in.

How to react to IsSelected in the DataTemplate

If you want to change the appearance of a ListBoxItem when it is selected, you have to bind the IsSelected property of the ListBoxItem. But this is a bit tricky, you have to use a relative source with FindAcestor to navigate up the visual tree until you reach the ListBoxItem.

<DataTemplate x:Key="DefaultDataTemplate">
    <Border x:Name="border" Height="50">
        <DataTrigger Binding="{Binding RelativeSource=
            {RelativeSource Mode=FindAncestor, AncestorType=
                {x:Type ListBoxItem}},Path=IsSelected}" Value="True">
            <Setter TargetName="border" Property="Height" Value="100"/>
Data Binding Specifics
To use WPF data binding, you must always have a target and a source. The target of the binding can be any accessible property or element that is derived from DependencyProperty—an example is a TextBox control’s Text property. The source of the binding can be any public property, including properties of other controls, common language runtime (CLR) objects, XAML elements, ADO.NET DataSets, XML Fragments, and so forth. To help you get the binding right, WPF includes two special providers—the XmlDataProvider and the ObjectDataProvider.
Now let’s take a look at how the WPF data-binding techniques work and I’ll present practical examples that illustrate their use.

ObservableCollection and IPropertyNotifyChanged January 17, 2012

Filed under: INotifyPropertyChanged,Observable Collection,WPF — sladescross @ 6:10 pm

These threads might help you:

When using an observable collection, you should always use a collection view source as well. Then reference to that collectionViewSource as your itemsSource. With this your items will update automatically if you implemented the INotifyPropertyChanged interface properly.

If not, you can also use CollectionViewSource.View.Refresh() to update all items of your collectionViewSource.


WPF ComboBox BreakDown Into WPF Classes December 1, 2011

Introduction to all aspects of WPF binding.

Data binding overview.

CodePlex solid introduction to data binding.

Run through of the different ways of notifying a data change in WPF

To bind the data to ComboBox

List<ComboData> ListData = new List<ComboData>(); 
ListData.Add(new ComboData { Id = "1", Value = "One" }); 
ListData.Add(new ComboData { Id = "2", Value = "Two" }); 
istData.Add(new ComboData { Id = "3", Value = "Three" }); 
ListData.Add(new ComboData { Id = "4", Value = "Four" }); 
ListData.Add(new ComboData { Id = "5", Value = "Five" }); 
cbotest.ItemsSource = ListData; 
cbotest.DisplayMemberPath = "Value"; 
cbotest.SelectedValuePath = "Id"; 
cbotest.SelectedValue = "2";

Recently, I received a question from one of my twitter tribemates on using the ComboBox in WPF with objects, and it centered around the difference between the SelectedValue, SelectedValuePath, and SelectedItem properties. This post will go through the differences, and how they are used, and also do a little review on databinding in WPF.

Specific example of parent detail binding in both directions.

Now, all of that aside, let’s go over the more common properties used in DataBinding to a Selector control.  Note that when I refer to the ViewModel I’m assuming that the DataContext of the page is set to your ViewModel instance and that the ComboBox has inherited that DataContext.

  • DataContext (FrameworkElement) - The object which will be the default binding source for the ItemsSource, SelectedItem and SelectedValue properties.
  • DisplayMemberPath (ItemsControl) - As the Selector iterates through its list of items, if you don’t want to display the object’s .ToString() value you can specify a path to a property here.  For example, if the item is of type “Customer” (meaning your ItemsSource binds to an ObservableCollection<Customer> or similar property) which has a property @Name of type Name { FirstName, LastName } and you want to display the customer’s first name.  To do this, you would set DisplayMemberPath=”Name.FirstName”.
  • SelectedItem (Selector) – Binds the ACTUAL object in the ItemsControl which is selected (which would be your “Customer” object in the previous example).  If you want to bind the actual item, you can specify your binding property in your ViewModel here.  For example, SelectedItem=”{Binding Path=SelectedCustomer, Mode=TwoWay}” would bind the selected Customer object to the SelectedCustomer property in your ViewModel (and since I didn’t specify a binding source, that would default to the DataContext).
  • SelectedValue & SelectedValuePath (Selector) - Specifies the binding which the property from the selected item at the path provided in SelectedValuePath should be bound to.  Using our customer example, if you wanted to bind the selected customer’s @Name.FirstName property to a property named SelectedCustomerFirstName on your ViewModel, you would set your SelectedValue=”{Binding SelectedCustomerFirstName}” and SelectedValuePath=”Name.FirstName”.

WPF Tree Visualiser

WPF debugging.

<Window xmlns:diag=”clr-namespace:System.Diagnostics;assembly=WindowsBase” />

<TextBlock Text=”{Binding Path=x, diag:PresentationTraceSources.TraceLevel=High}” />

SelectedItem binding to last item using CollectionView override.

Selected Value Path property binding.

Binding in code.

Binding b = new Binding();
b.Source = pre;
b.Path = new PropertyPath(“DisplayName”);
b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
b.Mode = BindingMode.TwoWay;
this.SetBinding(IdentityCard.DisplayNameProperty, b);

public override bool Equals(object otherObject)    

 {         if (!(otherObject is ActivityStatus))

 return false;        

 return Equals(otherObject as ActivityStatus);     }    

 public bool Equals(ActivityStatus otherStatus)     {       

  if (!(otherStatus is ActivityStatus) ||            

otherStatus == null) return false;        

 return Id == otherStatus.Id &&          

   Name == otherStatus.Name;     }

<StackPanel Name=”mainStackPanel”>
        <ListBox ItemsSource=”{Binding}” DisplayMemberPath=”Name” SelectedValue=”Messenger of the Gods” SelectedValuePath=”Description” Name=”listBox1″ (…) />

The difference between SelectedValue and SelectedItem should be obvious now. SelectedValue returns the string it was set to (“Messenger of the Gods”), while SelectedItem returns the actual GreekGod object with that description.

    string messengerOfGods = (string)(listBox1.SelectedValue);
    GreekGod hermes = (GreekGod)(listBox1.SelectedItem);

SelectedValue is particularly useful when only part of your item is stored in the model you are data binding to. In this scenario, you would data bind the SelectedValue property to the partial information in your model but the ListBox can show a lot more information about that item.


WPF Binding and Value Converter for Default Value November 3, 2011

Filed under: Binding,Value Convertor,WPF,WPF Binding — sladescross @ 5:28 pm

ValueConverters sit between the source value and the bound target property, and their sole purpose is to take a value and supply a different value.

The IValueConverter interface contains the following methods that must be implemented:

Collapse | Copy Code
object Convert(object value, Type targetType, object parameter, CultureInfo culture)

Which is used to convert from the source object into the new value which will be used by the target

Collapse | Copy Code
object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)

Which is used to convert from the target object back to the source. This will be used where a Bindings Binding.Mode has been set to TwoWay or OneWayToSource. More often than not, this will not be used, and will simply throw an exception.

So how do we use these ValueConverters in our code? Well, quite simply, we use the normal Bindings expression, but we also state which converter to use for the Binding.Converter property. Let’s see an example, shall we?

<Rectangle Width=”50″
                    Height=”25″ Margin=”5,0,0,0″
                    Fill=”{Binding ElementName=txtSource, Path=Text,
                    Converter={StaticResource wordToColorConv}}” />


WPF Binding Triggers

Filed under: Trigger,WPF,WPF Binding,WPF Source Trigger — sladescross @ 12:20 pm



WPF XML Binding and Namespaces September 30, 2011

Filed under: Local-Name,WPF,XMLNameSpaceManager — sladescross @ 11:37 am

I suppose after looking at the code, you should be able to understand why it works after specify the Binding.XmlNamespaceManager attached property for TextBlock.

ListBox is data bound to a data provider which has xml namespace mapping information, but the binding on the TextBlock doesn’t have this information, that’s why it fails.

Actually, when doing master detail data binding, it’s more appropriate to do something like the following:

<Page xmlns=”;
        <XmlNamespaceMappingCollection x:Key=”namespaceMappings”>
            <XmlNamespaceMapping Uri=”; Prefix=”p”/>
        <XmlDataProvider x:Key=”dataProvider”
                         XmlNamespaceManager=”{StaticResource namespaceMappings}”
                <p:players xmlns:p=””&gt;
                        <p:fullName>Sebastian Batistuta</p:fullName>
                        <p:fullName>Andriey Shevchenko</p:fullName>
                        <p:fullName>Paviel Nedved</p:fullName>
                        <p:fullName>David Beckham</p:fullName>
    <StackPanel DataContext=”{Binding Source={StaticResource dataProvider}}”>
            Text=”{Binding XPath=p:fullName}”
        <ListBox ItemsSource=”{Binding}”

<TextBox Name=”nameText”> 
       <Binding XPath=”*[local-name()='Name']” /> 


WPF Fast Start September 28, 2011

Filed under: IDataErrorInfo,INotifyPropertyChanged,Validation,WPF — sladescross @ 8:35 am

System.Windows + XAML

Simple binding. 3 alternate ways to bind the business object to the presentation.

Using only C# [INotifyPropertyChanged]
The typical approach is pretty cumbersome. The same result can be achieved by implementing the INotifyPropertyChanged interface in the Examinee class to generate an event everytime the value in the object’s property changes. I have highlighted portions in code listing 4 that need to be added to implement INotifyPropertyChanged.

With the above approach then you do not need to gather data changes from the business object but you do need to implement event handlers to move data from the user interface properties to the business object and delegate to handle the property changed events from the business object.

Using C# and XAML [INotifyPropertyChanged and XAML]
Both the approaches described above were used with typical Windows applications, although I created the form using XAML. The final approach (and the right one at that) uses the Data Binding syntax in XAML, and would show you how easy it is to bind UI elements directly to an object that implements INotifyPropertyChanged.


In this article, you’ll see how to use the IDataErrorInfo interface implementation, ValidationRules, BindingGroups, exceptions, and validation-related attached properties and events to address your data-validation needs. You’ll also see how to customize the display of validation errors with your own ErrorTemplates and ToolTips.

I’m talking about WPF Validation Rules. Validation Rules are objects that apply validation over a data Binding operation, and they are added to the Binding.ValidationRules Collection. They can be created by deriving from the ValidationRule class and overriding its Validate method that should hold the validation logic. Then, normally, you would add the rule to the collection in your xaml code, through property element syntax, or in code.

Although not a part of this article, there’s another validation mechanism built into WPF. You can also test one’s input through an ExceptionValidationRule, which invalidates a value if there are exceptions during source updates of the binding source property. You can even provide custom logic to specify how the binding engine handles these exceptions by using a UpdateSourceExceptionFilterCallback.

 In the previous article I’ve shown how to apply Validation Rules to controls in order to prevent/access user input. In the process, user was warned through a visual change in the target control. It’s the simplistic and direct way of doing validation and works perfectly from the UX point of view. However, from the developer point of view, a better implementation is required to ease the quantity of code needed and to isolate concerns.

The idea is to apply validation rules by means of an attached property, in which the owner would have the reference to the control and its target Dependency Property, and the required logic to add the rule object implicitly.

Simplify validation code by subclassing the Binding.

So what’s the trick when we wish to replace the good old Binding class by a custom one? The Binding class, like many others also familiar to you like StaticResource, DynamicResource, RelativeSource or Templatebinding, is a MarkupExtension. You can detect MarkupExtensions in XAML by the curly braces. They are the actual indicator of a markup to the XAML parser. So the idea here is to create a new binding-like MarkupExtension and extend it to accommodate binding functionality with built in validation.



WPF Validation September 22, 2011

Filed under: Validation,WPF,WPF Validation — sladescross @ 8:37 am

Detailed coverage.

There are two things worth mentioning here. The one is related to the way the object is initialized. Note that there is no constructor in the Client class.In C#3.0 you can initialize the properties of an object during construction in blocks of code enclosed by {}. Neat isn’t it? Also note that due to the hierarchical nature of the DataContext property, we can set the Window’s DataContext property to the Client Business Object and be sure that the bindings will find their paths ;)

Type conversion errors (case 1) must throw exceptions and the exceptions must be caught by the GUI. Type conversion errors are serious and they are justified to be raising exceptions. In WPF, a type conversion error exception of this kind is raised by default in a data bound TextBox Control and by default it is ignored. In order to catch the exception you need to set the property ValidatesOnExceptions to True (here it is done for the Rating textbox):

<TextBoxText=”{Binding Path=Rating,ValidatesOnExceptions=True}”>

This will display a red border around the TextBox when the entered value cannot be converted to the type of the Rating property (integer)- that is – an exception has been thrown. So far so good. But we may need to inform the user by providing a more descriptive message. For this reason, we hook up to the Validation.Error event and set the tooltip’s value to the reported error in the event handler. We also need to explicitely state that the Binding object should be raising such events by setting the NotifyOnVaidationError property to true.

So we set the NotifyOnValidationError property to true and set the event handler for the Validation.Error event:

ValidatesOnDataError is the super star behind all this. By flipping this flag on, the databinding will be able to communicate with any data types that implement IDataErrorInfo. (You might also want to read more about Validation.Error event and NotifyOnValidationError.)

There is a good MSDN Magazine article on this topic, WPF Apps With The Model-View-ViewModel Design Pattern:

According to this article, in The Data Model and Repository section ( you will find a simple implementation. The Customer is the entity class and the ViewModel gets the error indicators from the entity.

You can use ValidationsRule to check data validity:

<TextBox x:Name="title" VerticalAlignment="Top" TextWrapping="Wrap" Grid.Column="1" MinWidth="20"> <TextBox.Text> <Binding Path="Title" UpdateSourceTrigger="LostFocus"> <Binding.ValidationRules> <Validators:StringRangeValidationRule MinimumLength="1" MaximumLength="30" ErrorMessage="Address is required and must be less than 30 letters." /> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox> 

WPF Tutorial September 6, 2011

Filed under: Data Binding,WPF — sladescross @ 10:18 am

I think that if you are honest, however, you will agree that the XAML fragment is much more expressive than the HTML fragment. It is intuitive. One of the reasons for this is that, generally speaking, the element tags map directly to Types and the attributes map to Properties on those Types. Since WPF’s class hierarchy was very carefully designed, you’ll find that many elements have the same available attributes. This consistency makes for smooth, natural learning.

WPF data binding series.



Get every new post delivered to your Inbox.

Join 63 other followers