Wednesday, May 27, 2009

Why doesn’t my WPF Trigger work? (... a peek into the Dependency Property evaluation process)

Imagine a simple situation where I have a blue rectangle:

<Rectangle Height="200" Width="300" Fill="Blue"/>

Now when I do a mouse over the rectangle, I want the color to turn to red - simple! The obvious choice in WPF is to add a property trigger. So that’s what I do.

<Style TargetType="Rectangle" x:Key="rectStyle">
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Fill" Value="Red" />
<Rectangle Height="200" Width="300" Fill="Blue"
Style="{StaticResource rectStyle}"/>

But it doesn’t work! What could be wrong? Perhaps the mouse over event isn’t firing on the rectangle for some reason? I debug the trigger using this cool technique and find that the trigger is firing alright. Then what on earth is the problem?

A closer look reveals the real issue. The culprit was the Fill="Blue" assignment! When evaluating the value of a dependency property, the dependency property system takes into consideration a few factors. The whole dependency property value evaluation process is shown below. Certain factors have priority over others as shown in Step 1 below.

Step 1: Determine Base Value
In the order of diminishing priority:
(a) Local Value
(b) Style triggers
(c) Template Triggers
(d) Style Setters
(e) Theme Style Triggers
(f) Theme Style Setters
(g) Inheritance
(h) Default Value

Step 2: Evaluate
– If Step 1 returns expression (DataBinding or DynamicResource), evaluate

Step 3: Apply Animation

Step 4: Coerce
- If CoerceValueCallback defined

Step 5: Validate
- If ValidateValueCallback defined

In the above example of the rectangle, the trigger (see Step 1b) that I set in the style, had lower priority when compared to the local value (see Step 1a), that is the Fill="Blue" assignment. That was the reason why the trigger value was ignored. So the result/output of Step 1 as far as the Fill property was concerned was the local value “Blue”. In this example, Steps 2-5 do not apply.

So how do I get my trigger to work? If I remove the local value assignment for Fill, and instead set that value within the style, then everything will work as expected because triggers (see Step 1b) have higher priority over style setters (see Step 1d).

<Style TargetType="Rectangle" x:Key="rectStyle">
<Setter Property="Fill" Value="Blue" />
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Fill" Value="Red" />
<Rectangle Height="200" Width="300"
Style="{StaticResource rectStyle}"/>

Now the trigger works as expected!

Monday, April 27, 2009

WPF Text to Animated Path

Not sure what to call this - slate control? Or Text Scribbler? May be, or perhaps just "text to animated path control" :). Anyway, I was playing around with the possibility of animating text in such a way that you can see the text being written as though with a pen or a piece of chalk. This is the end result...

You can get the source here. Just run the application, enter any text in the TextBox, and hit the button to see the text being scribbled down in an animated fashion. You can also choose the Font Family, and the Foreground of the text from the combo boxes.

This is what the application does when the button is clicked:
1) The text from the TextBox is converted into a PathGeometry using the FormattedText class (System.Windows.Media namespace). You can specify the Font Family, Font Size etc. and get the corresponding path.

2) A MatrixAnimationUsingPath is applied on the pen (the red color object in the screen shot above). The PathGeometry property of this animation is set to the value obtained from Step 1).

3) At this point, the pen will animate over the path, but nothing will be scribbled down. While the pen is being animated, a timer runs concurrently with an interval in milliseconds. Whenever the timer ticks, the current position of the pen is calculated, and a small dot (ellipse) is drawn at that point. This gives you the illusion of text being continuously written down with the pen.

That's it! Enjoy scribbling!

(Note: The sample supports multi-line scribbling as well. To test this out, just set AcceptsReturn to true on the TextBox (you may also need to set IsDefault to False on the Start Button so that it does not interfere with the return key meant for the TextBox). Now if you enter multiple lines within the TextBox and start scribbling, you get multi-line scribbling !)

Source: Get it here.

Thursday, April 23, 2009

Debugging Data Binding in WPF

What do you do when you suspect that a data binding is broken in your WPF application? Looking at the Output window for data binding exceptions can be helpful in many cases. However, there are cases where this does not help.

For example, below I have TextBox.Text bound to Slider.Value. But notice that the binding is OneWay.

<TextBox Text="{Binding ElementName=slider, Path=Value, Mode=OneWay}" Height="30" Width="100" Margin="10" />

<Slider Minimum="0" Maximum="100" Value="20" Margin="10" x:Name="slider" />

When I move the slider, the text in the TextBox shows the slider value as expected. Now I enter some text in the TextBox(which causes the binding to break since it is OneWay binding; but assume that I haven't realized that). I move the slider now, but the text in TextBox does not update. I suspect that the binding is broken. But how do I confirm that?

Simply looking at the Output Window in this case reveals nothing. What I've been doing until now is to add a dummy converter and set a break point in the Convert method. If the break point is not hit I know that the binding is broken. But that is really a long way of doing something that should be really done in a simpler way....

WPF 3.5 has a new property called PresentationTraceSources.TraceLevel that you can set on your data binding to get more detailed information on the binding in the Output Window. In fact, if you set the trace level to High you can get details on every step in the process of the binding.

So to the above code, I make two changes

  • Add a namespace reference to System.Diagnostics
  • Set PresentationTraceSources.TraceLevel=High on the binding I want to inspect.

<Window x:Class="DebugBindings.Window1"... xmlns:trace="clr-namespace:System.Diagnostics;assembly=WindowsBase">


<TextBox Text="{Binding ElementName=slider, Path=Value, Mode=OneWay, trace:PresentationTraceSources.TraceLevel=High}" Height="30" Width="100" Margin="10"/>

<Slider Minimum="0" Maximum="100" Value="20" Margin="10" x:Name="slider" />



Now when I inspect the Output Window after running the application, I can see step-by-step details of the data binding process.

Created BindingExpression (hash=17654054) for Binding (hash=44624228)
Path: 'Value'
BindingExpression (hash=17654054): Default update trigger resolved to LostFocus
BindingExpression (hash=17654054): Attach to System.Windows.Controls.TextBox.Text (hash=52727599)
BindingExpression (hash=17654054): Resolving source
BindingExpression (hash=17654054): Found data context element: (OK)
Lookup name slider: queried TextBox (hash=52727599)
BindingExpression (hash=17654054): Resolve source deferred

BindingExpression (hash=17654054): Resolving source
BindingExpression (hash=17654054): Found data context element: (OK)
Lookup name slider: queried TextBox (hash=52727599)
BindingExpression (hash=17654054): Activate with root item Slider (hash=54371668)
BindingExpression (hash=17654054): At level 0 - for Slider.Value found accessor DependencyProperty(Value)
BindingExpression (hash=17654054): Replace item at level 0 with Slider (hash=54371668), using accessor DependencyProperty(Value)
BindingExpression (hash=17654054): GetValue at level 0 from Slider (hash=54371668) using DependencyProperty(Value): '20'
BindingExpression (hash=17654054): TransferValue - got raw value '20'
BindingExpression (hash=17654054): TransferValue - implicit converter produced '20'
BindingExpression (hash=17654054): TransferValue - using final value '20'

If I now enter text in the TextBox, I can check the Output Window to confirm that the binding was indeed broken!

BindingExpression (hash=17654054): Deactivate
BindingExpression (hash=17654054): Replace item at level 0 with {NullDataItem}
BindingExpression (hash=17654054): Detach

The only down side is that you have to manually add this property to each binding that you want to inspect.

Monday, December 29, 2008

Discovering RelativeSource.PreviousData

When working with Data Binding in WPF, I have found the RelativeSource class very useful. This class is useful when you want to bind to a source relative to the binding target. For example you may want to bind the Width of a control to its Height. In this case RelativeSource.Self can be used. Or you may want to bind to an element that is an ancestor of the binding target. Here you would use RelativeSource.FindAncestor.

But there was another use of RelativeSource that I was not aware of until recently - RelativeSource.PreviousData. Let me explain where this might be useful. Say you have data bound an ItemsControl like a ListBox to a collection of data items. You have written a DataTemplate to define how each item must be displayed within the ItemsControl. Within the DataTemplate you have access to the current data item. But what if you also want access to the previous data item?

For example, you may be displaying the stock values for a company as a chart as shown below.

Each bar in the chart represents one data item within the ItemsControl. But within each item(above the bar), you also want to show the increase/decrease of the stock value when compared to the previous stock value. This is where RelativeSource.PreviousData is useful as shown below.

<DataTemplate x:Key="RecordTemplate">



<TextBlock Margin="3,0,0,3">


<MultiBinding Converter="{StaticResource RecordsDifferenceConverter}">


<Binding RelativeSource="{RelativeSource PreviousData}"/>






</ DataTemplate

In the above XAML snippet, the MultiValueConverter accepts the value of the current item and the value of the previous item, and returns the difference between the two. This is displayed above each bar in the chart.

The source code for this sample may be found here. Keep in mind that this is not a fully implemented chart – there are so many things missing. I just wanted to illustrate where RelativeSource.PreviousData may be useful.

Wednesday, October 29, 2008

Implicit Styles in Silverlight

WPF supports both explicit and implicit styles (application wide styles), while Silverlight supports only explicit styles. This means that in Silverlight when you define a style as a resource, you have to give it an explicit key, and call that key wherever you want the style to be applied. For example, if you have defined a TextBlock style in App.Resources, you have to explicity set the Style property on all TextBlocks within the application like this:

<TextBlock Text="Text1" Style="{StaticResource key1}"/>

<TextBlock Text="Text2" Style="{StaticResource key1}"/>

<TextBlock Text="Text3" Style="{StaticResource key1}"/>

This has been an issue Silverlight developers have been grappling with for a long time. The Silverlight 2 release (RTW) did not have a solution for this. Fortunately, the Silverlight Toolkit that has been released yesterday, comes with an ImplicitStyleManager that makes implicit styles possible in Silverlight. If you are not familiar with the Silverlight Toolkit, you can read about it here.

So, how do you make use of this?

1) Download the Silverlight Toolkit.

2) Copy Microsoft.Windows.Controls.Theming.dll that comes within the toolkit to your Silverlight project and add a reference to it.

3) Add a reference to the namespace within which the ImplicitStyleManager resides:

xmlns:theming="clr-namespace:Microsoft.Windows.Controls.Theming; assembly=Microsoft.Windows.Controls.Theming"

4) Now use the ApplyMode property to set implicit styling:

<StackPanel x:Name="stackPanel" theming:ImplicitStyleManager.ApplyMode="OneTime">

<TextBlock Text="Static Text 1" />

<TextBlock Text="Static Text 2" />


5) Of course, you should have defined the style somewhere in the resources collection as shown below:


<Style TargetType="TextBlock">

<Setter Property="Foreground" Value="Red" />

<Setter Property="FontSize" Value="20" />

<Setter Property="Margin" Value="5" />



Now you are good to go. The ImplicitStyleManager will ensure that the style is passed down to the TextBlock down the element tree.

If you dynamically add a TextBlock to the element tree (at run time), you will find that the TextBlock will not get the style. In this case, you will have to set ImplicitStyleManager.ApplyMode="Auto". But setting it to Auto can have a major performance impact, so use this sparingly.

There you go - implicit styles in Silverlight :).

Saturday, September 27, 2008

Silverlight 2 RCO is Out

Silverlight 2 RCO is Out! So that means that the Silverlight RTW (Release To Web) is round the corner. The RCO release is a developer-only runtime edition that will help developers to prepare their existing Silverlight 2 Beta 2 applications for the final release. Some points to note:
  • This RCO release is feature complete - so do not expect any more controls/features in the Silverlight 2 release. However more controls/features can be expected in future months to be built on top of Silverlight 2 (these will not be part of the core runtime).

  • Three new controls added - ComboBox, ProgressBar, and PasswordBox. These along with most other controls will be part of the Silverlight runtime (which means that these will not be needed to be downloaded with the Silverlight application).

  • The Silverlight runtime is still only 4.6MB in size.

  • The default control styles/templates have been modified.

  • Once Silverlight 2 is released, users with existing beta releases installed will automatically be upgraded to use the final version (also developer machines with RCO , I suppose).

  • A modal dialog MessageBox is now available.

  • System.Windows.Controls.Extended.dll renamed to System.Windows.Controls.dll

  • If you are using custom controls, remember that generic.xaml is now expected in the 'themes' folder rather than at the root of the project.

Saturday, August 30, 2008

Silverlight on the Desktop

Its been almost two months since I blogged - just haven't had the time. But tonight I just couldn't resist making this post. My brilliant colleague at IdentityMine, Sameer Thiruthikad has been spearheading work on an exciting Silverlight utility called Desklighter, and the Beta is now public.

What is the Desklighter? Well, ever wished you could package your Silverlight application into an stand alone executable that could work offline? That is precisely what the Desklighter enables you to do. Read the whole story here, and be sure to try it!