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

http://msdn.microsoft.com/en-us/library/ms741870.aspx

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.

http://wpftutorial.net/DataTemplates.html

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">
        ...
    </Border>
    <DataTemplate.Triggers>
        <DataTrigger Binding="{Binding RelativeSource=
            {RelativeSource Mode=FindAncestor, AncestorType=
                {x:Type ListBoxItem}},Path=IsSelected}" Value="True">
            <Setter TargetName="border" Property="Height" Value="100"/>
        </DataTrigger>
    </DataTemplate.Triggers>
</DataTemplate>
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

http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/26ce37cd-199d-406d-ad8f-acb60c10bde6/

These threads might help you:

http://forums.msdn.microsoft.com/en-US/wpf/thread/0914ccab-d4db-4a2c-9a8f-34844f21fe63/

http://forums.msdn.microsoft.com/en-US/search/?q=%20refresh%20observablecollection&forum=wpf

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

http://www.codeproject.com/KB/WPF/WpfDataBinding1.aspx

Introduction to all aspects of WPF binding.

http://msdn.microsoft.com/en-us/library/ms752347.aspx#basic_data_binding_concepts

Data binding overview.

http://www.codeproject.com/KB/WPF/GuidedTourWPF_3.aspx

CodePlex solid introduction to data binding.

http://blogs.msdn.com/b/wpfsdk/archive/2007/03/21/wha-happened-part-two-more-property-changes-in-wpf.aspx

http://blogs.msdn.com/b/wpfsdk/archive/2007/03/21/wha-happened-part-two-more-property-changes-in-wpf.aspx

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

http://stackoverflow.com/questions/561166/binding-wpf-combobox-to-a-custom-list

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"; 

http://japikse.blogspot.com/2008/10/wpf-combobox-selecteditem-selectedvalue.html

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.

http://blog.cylewitruk.com/2010/09/wpf-combobox-and-databinding-datacontext-itemssource-displaymemberpath-selecteditem-selectedvalue-selectedvaluepath/

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”.

http://msdn.microsoft.com/en-us/library/dd409789.aspx

WPF Tree Visualiser

http://stackoverflow.com/questions/2802662/any-reason-why-presentationtracesources-tracelevel-high-would-not-print-any-info

WPF debugging.

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

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

http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/195c61af-d658-461f-b509-733315807e05

SelectedItem binding to last item using CollectionView override.

http://www.telerik.com/community/forums/wpf/combobox/valuepath-property.aspx

Selected Value Path property binding.

http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/4efab5ae-0a12-48c3-b8bd-4acc73bfb10d

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);

http://stackoverflow.com/questions/6145511/two-way-binding-problem-with-wpf-combobox-using-mvvm

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;     }

http://bea.stollnitz.com/blog/?p=9

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

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

http://www.codeproject.com/KB/WPF/BeginWPF5.aspx

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

http://devcomponents.com/blog/?p=153

UpdateSourceTrigger

 

WPF XML Binding and Namespaces September 30, 2011

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

http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/cb6b22e7-3a48-425b-bbad-2575d2618968/

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=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;
      xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”&gt;
    <Page.Resources>
        <XmlNamespaceMappingCollection x:Key=”namespaceMappings”>
            <XmlNamespaceMapping Uri=”http://www.footballism.com/2005/SoccerPlayers&#8221; Prefix=”p”/>
        </XmlNamespaceMappingCollection>
       
        <XmlDataProvider x:Key=”dataProvider”
                         XmlNamespaceManager=”{StaticResource namespaceMappings}”
                         XPath=”p:players/p:player”>
            <x:XData>
                <p:players xmlns:p=”http://www.footballism.com/2005/SoccerPlayers”&gt;
                    <p:player>
                        <p:fullName>Sebastian Batistuta</p:fullName>
                        <p:age>26</p:age>
                    </p:player>
                    <p:player>
                        <p:fullName>Andriey Shevchenko</p:fullName>
                        <p:age>30</p:age>
                    </p:player>
                    <p:player>
                        <p:fullName>Paviel Nedved</p:fullName>
                        <p:age>21</p:age>
                    </p:player>
                    <p:player>
                        <p:fullName>David Beckham</p:fullName>
                        <p:age>19</p:age>
                    </p:player>
                </p:players>
            </x:XData>
        </XmlDataProvider>
    </Page.Resources>
    <StackPanel DataContext=”{Binding Source={StaticResource dataProvider}}”>
        <TextBlock
            Text=”{Binding XPath=p:fullName}”
            FontWeight=”Bold”/>
        <ListBox ItemsSource=”{Binding}”
                 x:Name=”listBox”
                 DisplayMemberPath=”p:fullName”
                 IsSynchronizedWithCurrentItem=”True”>
        </ListBox>
    </StackPanel>
</Page>

http://stackoverflow.com/questions/190102/xml-data-binding-with-namespaces

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

 

WPF Fast Start September 28, 2011

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

http://msdn.microsoft.com/en-us/library/ms748948.aspx#TheWindowClass

System.Windows + XAML

http://coredotnet.blogspot.com/2006/05/wpf-data-binding-tutorial.html

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.

http://msdn.microsoft.com/en-us/library/ms752347.aspx#what_is_data_binding

http://msdn.microsoft.com/en-us/library/ms752347.aspx#master_detail_scenario

http://msdn.microsoft.com/en-us/magazine/ff714593.aspx

Validation.

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.

http://blog.vascooliveira.com/wpf-input-validation-part-1-tutorial-and-examples/

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.

http://blog.vascooliveira.com/wpf-input-validation-part-2-attached-property-approach/

 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.

http://blog.vascooliveira.com/wpf-input-validation-part-3-markup-extensions/

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

http://www.codeproject.com/KB/WPF/wpfvalidation.aspx

Detailed coverage.

http://www.progware.org/Blog/post/Data-Validation-in-WPF.aspx

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:

http://codeblitz.wordpress.com/2009/05/08/wpf-validation-made-easy-with-idataerrorinfo/

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.)

http://stackoverflow.com/questions/341792/using-idataerrorinfo-in-m-v-vm

There is a good MSDN Magazine article on this topic, WPF Apps With The Model-View-ViewModel Design Pattern: http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

According to this article, in The Data Model and Repository section (http://msdn.microsoft.com/en-us/magazine/dd419663.aspx#id0090102) 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

http://dotnetslackers.com/articles/silverlight/WPFTutorial.aspx#s1

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.

http://bea.stollnitz.com/blog/

WPF data binding series.

 

 
Follow

Get every new post delivered to your Inbox.

Join 63 other followers