Monthly Archives: July 2013

TemplateBinding can be a little too lightweight

TemplateBinding can be used within a ControlTemplate to reference a value from the control that the template has been implemented on, but it has a few issues associated with it.

On the plus side

TemplateBinding is evaluated at compile time giving an increase in performance.

On the negative side

TemplateBinding is a little lightweight on features and in what it can bind to or more specifically how it’s binds. It doesn’t offer all the capabilities of the Binding, for example you cannot apply converters, it doesn’t support two-way binding and most importantly it doesn’t handle the type converting that Binding implements.

So for example

<TextBlock Text="{TemplateBinding MyInteger}" />

where (you guessed it) MyInteger is an int, nothing will be output in this TextBlock. As it cannot convert an int to a string.

Luckily there’s another way of binding to the template using the slightly more verbose TemplatedParent option

<TextBlock Text="{Binding MyInteger, RelativeSource={RelativeSource TemplatedParent}}" />

Unlike the TemplateBinding this is evaluated at runtime and by using the Binding class we can all the goodness associated with Binding.

Designer Metadata – WPF Control Development

When creating a control in WPF the aim is to try to separate the UI from the functionality that implements the control logic. That is to say, create a “lookless” control. A lookless control may potentially have one or more of the following: functionality, properties, events, styles and visual state. The control itself should not know about how it’s displayed but may well know what part’s it might wish to manipulate (and what base types they are).

We want to publish the parts of the control that may be manipulated by a ControlTemplate so that a designer application, such as Visual Studio’s built-in WPF UI designer or Expression Blend, can find out which parts the control manipulates or what styles are used or what states exist within the control.

The following attributes are applied to a control’s class definition to publish various pieces of metadata.

TemplatePart Attribute

A control may be thought of as broken up into sections, for example maybe we’ve created a colour picker type of control which has a section made up of a selection of rectangles each showing a colour and possibly another section which is some for of input (let’s assume a TextBox) which is used to take the hexadecimal representation of a colour.

Within our code we’d declare these parts as follows:

[TemplatePart(Name = PART_HexadecimalInput, Type = typeof(TextBox))]
[TemplatePart(Name = PART_ColourSelectionPanel, Type = typeof(Panel))]
public class ColourPicker : Control
{
   private const string PART_HexadecimalInput = "PART_HexadecimalInput";
   private const string PART_ColourSelectionPanel = "PART_ColourSelectionPanel";

   // implementation
}

Note: The general rule is to name such parts by prefixing with PART_

Now within our implementation of the control we will have some code to get the various parts from the ControlTemplate applied to this control. This is usually handled in the OnApplyTemplate method as per the following

public override void OnApplyTemplate()
{
   base.OnApplyTemplate();

   hexadecimalInput = GetTemplateChild(PART_HexadecimalInput) as TextBox;
   colourSelectionPanel = GetTemplateChild(PART_ColourSelectionPanel) as Panel;
}

Assuming hexadecimalInput is of type TextBox and colourSelectionPanel is a Panel, we now have access to the parts that potentially make up the ControlTemplate. I say potentially because it’s equally possible that somebody re-templates to include only limited functionality, so for example maybe we just want the colour picker then we remove the PART_HexadecimalInput from our ControlTemplate. Thus this code should handle situations where a part is not found in the template.

Once the control has access to the parts (and assuming they exist in the ControlTemplate) we can now attached event handlers to them or manipulate them in different ways.

StyleTypedProperty Attribute

The StyleTypedProperty exposes the properties which are of type Style, for example we wish to extend our ColourPicker to have a property that has the Style applied to the colour selection panel. We declare the property as per any other dependency property (I’ll list below just for completeness)

public static readonly DependencyProperty ColourSelectionPanelStyleProperty =     
                 DependencyProperty.Register(
                 "ColourSelectionPanelStyle",
                 typeof(Style),
                 typeof(ColourPicker),
                 new PropertyMetadata(null));

public Style ColourSelectionPanelStyle
{
   get { return (Style)GetValue(ColourSelectionPanelStyleProperty ); }
   set { SetValue(ColourSelectionPanelStyleProperty , value); }
}

So now we have a property of type Style named ColourSelectionPanelStyle. We want to now expose this via the StyleTypedPropertyAttribute as per

[StyleTypedProperty(Property = "ColourSelectionPanelStyle", StyleTargetType = typeof(Panel))]
public class ColourPicker : Control
{
   // implementation
}

Exposing our style like this means we could easily apply, just the style, to part of our control without the need to clone the whole ControlTemplate.

TemplateVisualState Attribute

In a previous post I talked about using the VisualStateManager (VSM) and how we can create our own strings to represent a control’s different state. These strings are keys defined by the developer to represent various changes within a control.

To publish these states we use the TemplateVisualStateAttribute, for example

[TemplateVisualState(Name = "ColourSelected", GroupName = "SelectionStates")]
public class ColourPicker : Control
{
   // implementation
}

Now within our ControlTemplate we might have a VSM with the VisualState

<VisualStateManager.VisualStateGroups>
   <VisualStateGroup x:Name="ColourPickerGroup">
      <VisualState x:Name="ColourPickedState">
         <!-- Some UI specific code -->
      </VisualState>
   </VisualStateGroup>
</VisualStateManager.VisualStateGroups>

ContentProperty Attribute

The ContentPropertyAttribute can be used to indicate which property is the XAML content property. We might be hard pushed to find a use for the ContentProperty on our example ColourPicker, so instead let’s look at a ResourceKeyConverter class

[ContentProperty("Options")]
public class ResourceKeyConverter : MarkupExtension, IValueConverter
{
   public ResourceDictionary Options { get; set; }
   // implementation
}

Now XAML knows that within the ResourceKeyConverter XAML code the content is of type ResourceDictionary, for example

<UI:ResourceKeyConverter x:Key="resourceConverter">
   <ResourceDictionary>
      <SolidColorBrush Color="Red" x:Key="X" />
      <SolidColorBrush Color="Green" x:Key="Y" />
   </ResourceDictionary>
</UI:ResourceKeyConverter>

If the type of the property is not a string or object the XAML procesoor tries to convert the type using native type conversions or look for a type converter.

VisualStateManager and alternative to Triggers

The VisualStateManager came into being with Silverlight. I’m not a Silverlight developer, but I believe I’m right it saying that Silverlight didn’t support Triggers, hence the VSM was created to emulate aspects of the triggering system (or at least a state change management).

Where the VSM comes into it’s own is the ability to create a control with multiple “states”. Whereby when an event or other state change occurs we can inform the ControlTemplate via a simple string (used to define a state change key). This is similar to various MessageBus implementations for MVVM code. The VSM is literally a simple state machine, so not only can we handle the state changes but also the transitions between changes if we want. Offering the ability to not only change the UI on certain state changes but even do different things depending upon the transitions from state to state.

Note: Bot the Triggering system and the VSM can used toegether if desired.

Let’s see this in action as it’ll make things much clearer. I’ve implemented a simple WatermarkTextBox, initially using Triggers. When the textbox has focus the watermark text is hidden. When the textbox doesn’t have focus AND no text exists within the textbox, the watermark is displayed, otherwise it remains hidden. Here’s the XAML for the control

<Style TargetType="Controls:WatermarkTextBox" BasedOn="{StaticResource {x:Type TextBox}}">
   <Setter Property="Template">
      <Setter.Value>
         <ControlTemplate TargetType="Controls:WatermarkTextBox">
            <Grid>
               <Border BorderThickness="{Binding Path=BorderThickness, 
                   RelativeSource={RelativeSource TemplatedParent}, 
                   Mode=OneWay}" BorderBrush="{Binding Path=BorderBrush, 
                   RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay}">
                  <Grid>                               
                     <ScrollViewer x:Name="PART_ContentHost" Margin="3"/>
                     <TextBlock x:Name="PART_Watermark" 
                         Text="{TemplateBinding Watermark}" FontStyle="Italic" 
                         VerticalAlignment="Center" Margin="5,0,0,0" 
                         FontWeight="Bold" Foreground="Gray"/>
                  </Grid>
               </Border>
            </Grid>

            <ControlTemplate.Triggers>
               <MultiTrigger>
                  <MultiTrigger.Conditions>
                     <Condition Property="IsFocused" Value="True"/>
                  </MultiTrigger.Conditions>
                  <Setter Property="Visibility" 
                            Value="Collapsed" TargetName="PART_Watermark" />
               </MultiTrigger>

               <MultiTrigger>
                  <MultiTrigger.Conditions>
                     <Condition Property="RemoveWatermark" Value="True"/>
                     <Condition Property="IsFocused" Value="False"/>
                  </MultiTrigger.Conditions>
                  <Setter Property="Visibility" 
                            Value="Collapsed" TargetName="PART_Watermark" />
               </MultiTrigger>
            </ControlTemplate.Triggers>

         </ControlTemplate>
      </Setter.Value>
   </Setter>
</Style>

and now the bare bones source code for this implementation looks like this

public class WatermarkTextBox : TextBox
{
   static WatermarkTextBox()
   {
      DefaultStyleKeyProperty.OverrideMetadata(typeof(WatermarkTextBox), 
              new FrameworkPropertyMetadata(typeof(WatermarkTextBox)));

      TextProperty.OverrideMetadata(typeof(WatermarkTextBox),
   	      new FrameworkPropertyMetadata(
                  new PropertyChangedCallback(TextPropertyChanged)));
   }	

   public static readonly DependencyProperty WatermarkProperty =
	DependencyProperty.Register("Watermark", typeof(string), 
           typeof(WatermarkTextBox),
	   new FrameworkPropertyMetadata(String.Empty));

   public string Watermark
   {
      get { return (string)GetValue(WatermarkProperty); }
      set { SetValue(WatermarkProperty, value); }
   }

   private static readonly DependencyPropertyKey RemoveWatermarkPropertyKey
            = DependencyProperty.RegisterReadOnly("RemoveWatermark", 
                    typeof(bool), typeof(WatermarkTextBox),
                    new FrameworkPropertyMetadata((bool)false));

   public static readonly DependencyProperty RemoveWatermarkProperty
            = RemoveWatermarkPropertyKey.DependencyProperty;

   public bool RemoveWatermark
   {
      get { return (bool)GetValue(RemoveWatermarkProperty); }
   }

   static void TextPropertyChanged(DependencyObject sender, 
                     DependencyPropertyChangedEventArgs args)
   {
      WatermarkTextBox watermarkTextBox = (WatermarkTextBox)sender;
      bool textExists = watermarkTextBox.Text.Length > 0;
      if (textExists != watermarkTextBox.RemoveWatermark)
      {
         watermarkTextBox.SetValue(RemoveWatermarkPropertyKey, textExists);
      }
   }
}

Now let’s look at an equivalent ControlTemplate using the VSM

<Style TargetType="Controls:WatermarkTextBox" BasedOn="{StaticResource {x:Type TextBox}}">
   <Setter Property="Template">
      <Setter.Value>
         <ControlTemplate TargetType="Controls:WatermarkTextBox">
            <Grid>
              <VisualStateManager.VisualStateGroups>
                 <VisualStateGroup x:Name="WatermarkGroup">
                    <VisualState x:Name="ShowWatermarkState">
                        <Storyboard>
                           <ObjectAnimationUsingKeyFrames 
                                       Duration="0:0:0" 
                                       Storyboard.TargetName="PART_Watermark" 
                                       Storyboard.TargetProperty="(UIElement.Visibility)">
                              <DiscreteObjectKeyFrame KeyTime="0:0:0" 
                                       Value="{x:Static Visibility.Visible}"/>
                           </ObjectAnimationUsingKeyFrames>
                        </Storyboard>
                        </VisualState>
                        <VisualState x:Name="HideWatermarkState">
                           <Storyboard>
                              <ObjectAnimationUsingKeyFrames Duration="0:0:0" 
                                        Storyboard.TargetName="PART_Watermark" 
                                        Storyboard.TargetProperty="(UIElement.Visibility)">
                                 <DiscreteObjectKeyFrame KeyTime="0:0:0" 
                                          Value="{x:Static Visibility.Collapsed}"/>
                              </ObjectAnimationUsingKeyFrames>
                           </Storyboard>
                        </VisualState>
                 </VisualStateGroup>
              </VisualStateManager.VisualStateGroups>

               <Border BorderThickness="{Binding Path=BorderThickness, 
                   RelativeSource={RelativeSource TemplatedParent}, 
                   Mode=OneWay}" BorderBrush="{Binding Path=BorderBrush, 
                   RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay}">
                  <Grid>                               
                     <ScrollViewer x:Name="PART_ContentHost" Margin="3"/>
                     <TextBlock x:Name="PART_Watermark" 
                         Text="{TemplateBinding Watermark}" FontStyle="Italic" 
                         VerticalAlignment="Center" Margin="5,0,0,0" 
                         FontWeight="Bold" Foreground="Gray"/>
                  </Grid>
               </Border>
            </Grid>
         </ControlTemplate>
      </Setter.Value>
   </Setter>
</Style>

Now the source code is basically the same as previously listed but with the following change to TextPropertyChanged

static void TextPropertyChanged(DependencyObject sender, 
                  DependencyPropertyChangedEventArgs args)
{
   WatermarkTextBox watermarkTextBox = (WatermarkTextBox)sender;
   bool textExists = watermarkTextBox.Text.Length > 0;
   if (textExists != watermarkTextBox.RemoveWatermark)
   {
      watermarkTextBox.SetValue(RemoveWatermarkPropertyKey, textExists);
   }

   // added to update the VSM
   watermarkTextBox.UpdateState();
}

and the following new methods

private void UpdateState()
{
   bool textExists = Text.Length > 0;
   var watermark = GetTemplateChild("PART_Watermark") as FrameworkElement;
   var state = textExists || IsFocused ? "HideWatermarkState" : "ShowWatermarkState";

   VisualStateManager.GoToState(this, state, true);
}

protected override void OnGotFocus(RoutedEventArgs e)
{
   base.OnGotFocus(e);
   UpdateState();
}

protected override void OnLostFocus(RoutedEventArgs e)
{
   base.OnLostFocus(e);
   UpdateState();
}

So we’ve had to put a little extra work into the VSM version, but the key bit is in UpdateStatus where we tell the VSM to GoToState. In this we’re in essence sending a string message to the VSM to tell it to “trigger” it’s storyboard for the given state.

What this means is that we could define many changes in state that could then be handled via the VSM.

We could (as seems to occur in some controls) define states which our ControlTemplate does nothing with. This allows us to define states within the control’s code which somebody might wish to hook into. These might be declared in the default ControlTemplate as empty elements as per the code below

<VisualState x:Name="DoSomethingSomeDay" />

Then anyone defining their own ControlTemplate can override these states if they wish.

When defining our states a control should publish the states that it implements.uses using the TemplateVisualState attribute. This is not a requirement for the code to work bbut obviously tells anything/anyone wishing to retemplate the control, what states it codes to, so for our example we would mark the WatermarkTextBox thus

[TemplateVisualState(Name = "ShowWatermarkState", GroupName = "WatermarkGroup")]
[TemplateVisualState(Name = "HideWatermarkState", GroupName = "WatermarkGroup")]
public class WatermarkTextBox : TextBox
{
   // .. implementation
}

Along with the ability to set different visual states we can also create transitions (VisualTransitions) between two states, for example if a state changes from one state to another maybe we want to change the colour of the background of a control to show the transition. In some ways we can achieve most of what we want in the various VisualStates, but the VisualTransition can show difference based on the different workflows of a state transition.

Below is a simple example for the WatermarkTextBox, which could have been achieved solely with states, but just gives an idea of what you can do. Here we transition between ShowWatermarkState and HidewatermarkState and back. Using a DoubleAnimation we alter the Opacity of the watermark text.

<VisualStateManager.VisualStateGroups>
   <VisualStateGroup x:Name="WatermarkGroup">
       <VisualStateGroup.Transitions>
           <VisualTransition From="ShowWatermarkState" To="HideWatermarkState">
              <Storyboard>
                 <DoubleAnimation Storyboard.TargetName="PART_Watermark"
                                  Storyboard.TargetProperty="Opacity" From="1"
                                  To="0" Duration="0:0:2" />
               </Storyboard>                                        
            </VisualTransition>
            <VisualTransition From="HideWatermarkState" To="ShowWatermarkState">
               <Storyboard>
                  <DoubleAnimation Storyboard.TargetName="PART_Watermark"
                                   Storyboard.TargetProperty="Opacity" From="0"
                                   To="1" Duration="0:0:2" />
               </Storyboard>
            </VisualTransition>
         </VisualStateGroup.Transitions>
         <VisualState x:Name="ShowWatermarkState">
            <Storyboard>
               <ObjectAnimationUsingKeyFrames Duration="0:0:0" 
                             Storyboard.TargetName="PART_Watermark" 
                             Storyboard.TargetProperty="(UIElement.Visibility)">
                  <DiscreteObjectKeyFrame KeyTime="0:0:0" 
                             Value="{x:Static Visibility.Visible}"/>
               </ObjectAnimationUsingKeyFrames>
            </Storyboard>
         </VisualState>
         <VisualState x:Name="HideWatermarkState">
            <Storyboard>
               <ObjectAnimationUsingKeyFrames Duration="0:0:0" 
                             Storyboard.TargetName="PART_Watermark" 
                             Storyboard.TargetProperty="(UIElement.Visibility)">
                   <DiscreteObjectKeyFrame KeyTime="0:0:0" 
                             Value="{x:Static Visibility.Collapsed}"/>
               </ObjectAnimationUsingKeyFrames>
            </Storyboard>
        </VisualState>                                
    </VisualStateGroup>
</VisualStateManager.VisualStateGroups>

Now the above will not work quite as expected on the first time the texbox gets focus as no transition takes place so in the code if we add

public override void OnApplyTemplate()
{
   base.OnApplyTemplate();
   VisualStateManager.GoToState(this, "ShowWatermarkState", true);
}

Just to seed the initial state, then as the textbox gets focus the transition from ShowWatermarkState to HideWatermarkState takes place.

DataTemplates and DataTriggers in WPF

One of the cool features of WPF is the way we can define a UI based upon the data type used.

For example, assuming a very simple view model

public class PersonViewModel : ReactiveObject
{
   private string firstName;
   private string lastName;
   private int age;

   public string FirstName
   {
      get { return firstName; }
      set { this.RaiseAndSetIfChanged(ref firstName, value); }
   }

   public string LastName
   {
      get { return lastName; }
      set { this.RaiseAndSetIfChanged(ref lastName, value); }
   }

   public int Age
   {
      get { return age; }
      set { this.RaiseAndSetIfChanged(ref age, value); }
   }
}

We might have a parent view model returning a PersonViewModel type or maybe an ItemsControl that has an ObservableCollection of PersonViewModel types. We can handle the bindings in the standard way but we can also associate a UI with a data type using DataTemplates.

A simple example of this is seem with the following code

<ResourceDictionary>
   <Model:PersonViewModel x:Key="model"/>
</ResourceDictionary>

<Button Content="{Binding Source={StaticResource model}}"/>

With the above the button content will display the namespace.objecttype, i.e. MyTestApp.PersonViewModel which is of little use, but if we create a DataTemplate as per the following XAML, we get something more useable

<DataTemplate DataType="{x:Type ta:PersonViewModel}">
   <TextBlock>                    
      <TextBlock.Text>
         <MultiBinding StringFormat="{}{0} {1} aged {2}">
            <Binding Path="FirstName" />
            <Binding Path="LastName" />
            <Binding Path="Age" />
         </MultiBinding>
      </TextBlock.Text>
   </TextBlock>
</DataTemplate>

Now our button will display the “FirstName LastName aged Age” text, where obviously FirstName, LastName and Age are taken from our view model.

Note: You can use a DataTemplate against any ContentControl, so we can see this template used on a button, a label or other control that expects/handles a ContentControl. Whereas the likes of a TextBlock’s Text property expects a string, so this will not work there.

The DataTemplate is also used in the ItemTemplate of a ListBox (for example)

<ListBox ItemsSource="{Binding People}" />

Using the above, where People is an ObservableCollection property. The ItemTemplate of the ListBox uses the DataTemplate previously defined. Alternatively we can create the DataTemplate within the ItemTemplate as per

<ListBox ItemsSource="{Binding People}">
   <ListBox.ItemTemplate>
      <DataTemplate>
         <TextBlock>
            <TextBlock.Text>
               <MultiBinding StringFormat="{}{0} {1} aged {2}">
                  <Binding Path="FirstName" />
                  <Binding Path="LastName" />
                  <Binding Path="Age" />
               </MultiBinding>
            </TextBlock.Text>
         </TextBlock>
      </DataTemplate>
   </ListBox.ItemTemplate>
</ListBox>

Along with DataTemplate we can define DataTemplate Triggers, for example

<DataTemplate DataType="{x:Type ta:PersonViewModel}">
   <TextBlock x:Name="text">                    
      <TextBlock.Text>
         <MultiBinding StringFormat="{}{0} {1} aged {2}">
            <Binding Path="FirstName" />
            <Binding Path="LastName" />
            <Binding Path="Age" />
         </MultiBinding>
      </TextBlock.Text>
   </TextBlock>
   <DataTemplate.Triggers>
      <Trigger SourceName="text" Property="IsMouseOver" Value="True">
         <Setter TargetName="text" Property="Background" Value="GreenYellow" />
      </Trigger>
   </DataTemplate.Triggers>
</DataTemplate>

So now anything use the DataTemplate will also apply the trigger code to the UI view of this data.

Styles in WPF

Styles in WPF allow us a reusable means of applying styling properties to controls. So for example, if we’ve decided that all the text boxes within a control, window or our app. should be displayed with a LemonChiffon background colour, instead of having something like this

<TextBox Background="LemonChiffon" x:Name="FirstName"/>
<TextBox Background="LemonChiffon" x:Name="LastName"/>
<TextBox Background="LemonChiffon" x:Name="Age"/>

we could create a style that’s applied to all TextBoxes, like the following

<ResourceDictionary>
   <Style TargetType="{x:Type TextBox}">
      <Setter Property="Background" Value="Gray" />
   </Style>
</ResourceDictionary>

...

<TextBox x:Name="FirstName"/>
<TextBox x:Name="LastName"/>
<TextBox x:Name="Age"/>

The style is defined as part of the ResourceDictionary and in this instance as no x:Key is set on the style resource it’s applied to all TextBoxes. If you were to create more than one style for a TextBox in this way, the last one defined is the one that will be used to style the TextBoxes. In such a situation where no key is defined, implicitly the key of x:Key=”{x:Type TextBox}” is used instead.

Note: We set the properties of the UIElement we wish to change using the Setter tag and the Property is obviously the property on the UIElement and the value is the value we wish to apply. I know, it’s obvious but I thought I’d mention it anyway.

So if you had a desire to have multiple background colours, for example maybe one colour for required fields and another for options, you would need to give one or both styles a key name to be used by the TextBox. For example

<Style x:Key="Required" TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
   <Setter Property="Background" Value="LemonChiffon" />
</Style>

<Style x:Key="Optional" TargetType="{x:Type TextBox}">
   <Setter Property="Background" Value="BlanchedAlmond" />
</Style>

...

<TextBox x:Name="FirstName" Style="{StaticResource Required}"/>
<TextBox x:Name="LastName" Style="{StaticResource Required}"/>
<TextBox x:Name="Age" Style="{StaticResource Optional}"/>

If the Optional key didn’t exist then all TextBoxes without a style applied will take on the style without a x:Key.

Styles can also inherit from other styles, so let’s say we want to inherit from the newly created Required style for a TextBox and create a style based on it but which also adds a Bold font. We use the BasedOn attribute

<Style x:Key="Important" TargetType="{x:Type TextBox}" BasedOn="{StaticResource Required}">
   <Setter Property="FontWeight" Value="Bold" />
</Style>

So the “Important” style now inherits the LemonChiffon background and adds the Bold font.

Styles, of course, can be placed in other assemblies and referenced via an application using the Pack URI for example, in my App.xaml I could reference the xaml from an assembly as follows

<Application.Resources>
   <ResourceDictionary Source="pack://application:,,,/MyAssembly;component/Themes/generic.xaml" />-->
</Application.Resources>

Note: Whilst this code works, it doesn’t display the style at design time via the XAML designer. It will display at runtime.

Along with the “basic” styles of a control we can declare other styling attributes such as Triggers.

<Style x:Key="Required" TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
   <Setter Property="Background" Value="LemonChiffon" />
   <Style.Triggers>
      <Trigger Property="IsMouseOver" Value="True">
         <Setter Property="Background" Value="GreenYellow" />
      </Trigger>
   </Style.Triggers>
</Style>

In the above we not add the trigger to change the background colour when the mouse is over the control.

Note: IsMouseOver comes from the UIElement.

Basics of extending a WPF control

Occasionally we need to extend an existing WPF control. We might apply a different style to the control, or applying a new control template both using XAML. Or maybe this isn’t sufficient and we need to add functionality to the control itself using code.

In this post we’ll not be touching the style, but we will be looking at extending an existing control’s functionality and changing the control template to use the new functionality. This result is not mean’t to be a production ready control (although hopefully it will be) but is more aimed at the steps required to create our new control etc.

Through this post we’ll create a simple watermark text box. In other word a text box which displays text, then when the control gets focus the text will disappear and when the control loses focus and only if no text has been typed in, the watermark will reappear.

The steps….

  1. Create a new control and derive from the WPF TextBox, create an initial style for the control and expose this to allows us to reference and use the control elsewhere.
  2. Add our new properties, such as a string property for the Watermark text and a flag to state whether text exists in the TextBox
  3. Create the new control template to work with the new control properies

Step 1

We’ve already decided that we want to simply added some functionality to an existing TextBox, so first we create a new class (in the file named WatermarkTextBox,cs) and derive it from TextBox.

public class WatermarkTextBox : TextBox
{
   static WatermarkTextBox()
   {
      DefaultStyleKeyProperty.OverrideMetadata(typeof(WatermarkTextBox), 
             new FrameworkPropertyMetadata(typeof(WatermarkTextBox)));
   }
}

The important addition here is the static constructor and the DefaultStyleKeyProperty.OverrideMetadata. Without this the WatermarkTextBox will get the default theme for the TextBox, but we know we’re going to need to change this, so this line sets the default style to one with a target type of WatermarkTextBox.

If you ran code with this class as it is, you’d seen no output as we’ve not defined the default style yet. If you comment out the line in DefaultStyleKeyProperty.OverrideMetadata you’ll obviously see the default style for a TextBox.

So to complete step 1. We need to create a .xaml file (named WatermarkTextBox.xaml), so in VS2012 add a new Resource Dictionary and then add the following code to it

<Style TargetType="Controls:WatermarkTextBox" BasedOn="{StaticResource {x:Type TextBox}}">
</Style>

You’ll obviously need to add the namespace, which I’ve named as Controls.

I’ve in essence defined a style for this control which obviously adds nothing and thus looks like a TextBox’s default style. But we’ll flesh this out later. For now this will display nothing unless we create a Generic.xaml file.

Themes\Generic.xaml

By default WPF expects any generic styles etc. to be stored in a folder named Themes off of the project. Here we create another Resource Dictionary file name Generic.xaml. To this we add the following code

<ResourceDictionary.MergedDictionaries>
   <ResourceDictionary Source="/SimpleControl;component/WatermarkTextBox.xaml" />
</ResourceDictionary.MergedDictionaries>

We’re telling WPF to merge the WatermarkTextBox.xaml file into the Themes\Generic.xaml Resource Dictionary.

Step 2

Step 1 was basically about getting the plumbing in place to allow us to work with our new control, so let’s now added some new functionality to the WatermarkTextBox. This step will write all the code in the .cs file so go to that file and type dpp and tab (twice) within the class to use the DependencyProperty code snippet that ships with VS2012. Select 0 — Dependency Property — default value.

Give the property the name Watermark. This will be the text displayed as the watermark. VS should fill in the name and create the snippet. We need to change the text new FrameworkPropertyMetadata((bool)false) to new FrameworkPropertyMetadata(String.Empty) so that this property is a string and by default displays an empty string, i.e. nothing. Also we need to change the from bool to string elsewhere.

So the code should look like this (comments and regions removed)

public static readonly DependencyProperty WatermarkProperty =
         DependencyProperty.Register("Watermark", typeof(string), 
                      typeof(WatermarkTextBox),
		      new FrameworkPropertyMetadata(String.Empty));

   public string Watermark
   {
      get { return (string)GetValue(WatermarkProperty); }
      set { SetValue(WatermarkProperty, value); }
   }

Now we want the watermark to disappear when the control gains focus which is easy enough, but we also want it so that when the control loses focus the watermark is redisplayed but only if no text exists. So we need a property to tell us whether text exists. It’s not something that can be altered outside of the class so under the Dependency Property we just added (and within the class) type dp and tab twice selecting the Read-Only Dependency Property — default value option. To added a read only dependency property.

Give the name RemoveWatermark and let the snippet fill in the rest. This code snippet added a SetRemoveWatermark method, we don’t need this as the value is going to be determined by whether there’s text in the TextBox and therefore cannot be set directly. The code added should therefore look like this (comments and regions removed).

private static readonly DependencyPropertyKey RemoveWatermarkPropertyKey = 
            DependencyProperty.RegisterReadOnly("RemoveWatermark", typeof(bool), 
                typeof(WatermarkTextBox),
                new FrameworkPropertyMetadata((bool)false));

public static readonly DependencyProperty RemoveWatermarkProperty =                 
            RemoveWatermarkPropertyKey.DependencyProperty;

public bool RemoveWatermark
{
   get { return (bool)GetValue(RemoveWatermarkProperty); }
}

Finally for the code we need to put the code in place to update RemoveWatermark. So we’ve already mentioned that this code will depend on there being text in the TextBox. So naturally we’ll need to override the TextPropertyChanged event. To do this we need to add the following code to the static constructor

TextProperty.OverrideMetadata(typeof(WatermarkTextBox),
	new FrameworkPropertyMetadata(new PropertyChangedCallback(TextPropertyChanged)));

This tells TextBox TextProperty to call our TextPropertyChanged event for WatermarkTextBox types. So now let’s add the TextPropertyChanged code

static void TextPropertyChanged(DependencyObject sender, 
                  DependencyPropertyChangedEventArgs args)
{
   WatermarkTextBox watermarkTextBox = (WatermarkTextBox)sender;

   bool textExists = watermarkTextBox.Text.Length > 0;
   if (textExists != watermarkTextBox.RemoveWatermark)
   {
      watermarkTextBox.SetValue(RemoveWatermarkPropertyKey, textExists);
   }
}

This is simple enough. The sender should always be of type WatermarkTextBox so we simply cast it. We then check whether the Text.Length is greater than zero to see whether text exists. If the RemoveWatermark property differs from the new value we set the value on the RemoveWatermarkPropertyKey.

If we run a test app with the WatermarkTextBox it will still look like a TextBox but now has extra properties so if you’re working through this example go to your test app and add a Watermark string to your WatermarkTextBox ready for the next step. So it looks something like this

<Controls:WatermarkTextBox Watermark="Search" />

Step 3

We now need to fill in the control’s style. Open the WatermarkTextBox.xaml file and insert the following code into the Style created previously

<Setter Property="Template">
   <Setter.Value>
      <ControlTemplate TargetType="Controls:WatermarkTextBox">
                    
         <Border BorderThickness="{Binding Path=BorderThickness, RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay}" 
                 BorderBrush="{Binding Path=BorderBrush, RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay}">
            <Grid>
               <ScrollViewer x:Name="PART_ContentHost" Margin="3"/>
                  <TextBlock x:Name="watermarkText" 
                        Text="{TemplateBinding Watermark}" 
                        FontStyle="Italic" 
                        VerticalAlignment="Center"
			Margin="5,0,0,0" 
                        FontWeight="Bold" 
                        Foreground="Gray"/>
             </Grid>
          </Border>
                    
         <ControlTemplate.Triggers>
            <MultiTrigger>
               <MultiTrigger.Conditions>
                  <Condition Property="IsFocused" Value="True"/>
               </MultiTrigger.Conditions>
               <Setter Property="Visibility" Value="Collapsed" TargetName="watermarkText" />
            </MultiTrigger>

            <MultiTrigger>
               <MultiTrigger.Conditions>
                  <Condition Property="RemoveWatermark" Value="True"/>
                  <Condition Property="IsFocused" Value="False"/>
               </MultiTrigger.Conditions>
               <Setter Property="Visibility" Value="Collapsed" TargetName="watermarkText" />
            </MultiTrigger>
         </ControlTemplate.Triggers>
      </ControlTemplate>
   </Setter.Value>
</Setter>

There’s a lot to take in there, but basically we’re setting the Template for the WatermarkTextBox. The first part is the ControlTemplate whereby we replace the TextBox’s default look with out own, adding a TextBlock which will display our Watermark text.

Note: The Textbox’s actually Template is far larger than the one shown above but basically we’re only really interested in the PART_ContentHost for this sample. But feel free to use Blend or whatever you prefer to edit the whole template if you wish.

As originally decided, we need this text to disappear when the control gets focus and reappear if the control loses focus AND there’s no text in the text box. So we create the two triggers.

The fist checks the IsFocused property and if it’s true collapses the water mark text. The second trigger checks whether we need to remove the watermark AND the IsFocused is False. If it is then the water mark is collapsed.

And that’s it, we’ve created a simple control, added properties, created the default style for the control and made it available to other code (outside it’s assembly).

Settings the DataContext in XAML and the ObjectDataProvider

I was updating a Tips & Tricks post on setting the DataContext via XAML and realised the post was getting way too large for a Tips & Tricks, so here’s the content in its own post.

So to set the DataContext in XAML we can do the following

<Window.DataContext>
   <Thermometer:ConversionViewModel />
</Window.DataContext>

This is simple enough, but there are various other ways to do this in XAML

ObjectDataProvider

The ObjectDataProvider allows us to create an object for use as a binding source within XAML. Unlike the Datacontext shown above, we declare the XAML for the ObjectDataProvider within the Window.Resources section as per

<Window.Resources>
   <ObjectDataProvider ObjectType="{x:Type Thermometer:ConversionViewModel}" x:Key="data">
      <ObjectDataProvider.ConstructorParameters>
         <system:Double>30</system:Double>
      </ObjectDataProvider.ConstructorParameters>
   </ObjectDataProvider>
</Window.Resources>

In the example above you’ll notice we can supply constructor parameters also.

We give the object a key for use in our bindings where we could just do something like

<Grid DataContext="{StaticResource data}">
...
</Grid>

or

<TextBlock Text={Binding Source={StaticResource data}, Path=Name}" />

The ObjectDataProvider also allows us to bind to a Method return value. So for example, what if we have the ObjectDataProvider similar to the one previously declared and we have a method named GetAge which takes a parameter (the name of the person who’s age we want returned). Like the previous example we can declare our ObjectDataProvider in the Resources section and it might look like this

<ObjectDataProvider ObjectInstance="{StaticResource data}" MethodName="GetAge" x:Key="age">
   <ObjectDataProvider.MethodParameters>
      <system:String>Bob</system:String>
   </ObjectDataProvider.MethodParameters>
</ObjectDataProvider>

Now we can bind to this data in the following way

<Label Content="{Binding Source={StaticResource age}}" />

Note: Just remember that the binding source is one way. So if you were to assign it to a two way by default control such as a TextBox, you’d get an error requiring you to set the binding to one way (not much use really on a text box).

But it would be much cooler if you could bind to the method and yet interact with the parameters at runtime, i.e. the user enters a person’s name (in our example) and the label updates to show the age of that person.

This can be achieved by creating a binding to the ObjectDataProvider object itself. By default we’ve seen that the interaction with the binding source allows us to pass straight through to the actual data the binding source contains, i.e. we do not appear to be using an ObjectDataProvider to bind to but instead the data source we assigned to it. If we could bind somehow to the ObjectDataProvider itself we could change the arguments passed to the method. This is how we do this…

<TextBox>
   <TextBox.Text>
      <Binding Source="{StaticResource age}" Path="MethodParameters[0]" BindsDirectlyToSource="true" />
   </TextBox.Text>
</TextBox>

As you can see above, we bind to the source as we’ve done previously but we now have a Path that points to the MethodParameters list and we’ve set the BindsDirectlyToSource to true. This tells the binding to evaluate the path on DataSourceProvider object (the ObjectDataProvider) as opposed to our data which is wrapped within the ObjectDataProvider.

Another thing to note about the code above, is that this works fine if the method parameter is a string (as in our example), but if it’s not then you’ll need to convert the type within the TextBox.Text binding source to the type expected by the method or you’ll simply find the method doesn’t get called.

For example

<TextBox.Text>
   <Binding Source="{StaticResource name}" 
                 Path="MethodParameters[0]" BindsDirectlyToSource="true" 
                 Converter="{MyConverters:ConvertTypeConverter To={x:Type system:Int32}}"/>
</TextBox.Text>

And finally…
Just to conclude this tip by also stating that you can also declare your view model in XAML as a resource as in the following

<Window.Resources>
   <Thermometer:ConversionViewModel InitialValue="30" x:Key="data" />
</Window.Resources>

The above shows how we can set properties on the view model as well.

Mutex – Running a single instance of an application

Occasionally you might want to create an application that can only have a single instance running on a machine at a time. For example, maybe you’ve a tray icon application or maybe an application that caches data for other applications to use etc.

We can achieve this by using a Mutex. A Mutex is very much like a Monitor/lock but can exist across multiple processes.

class Program
{
   static void Main(string[] args)
   {
      using(Mutex mutex = new Mutex(false, "some_unique_application_key"))
      {
         if(!mutex.WaitOne(TimeSpan.FromSeconds(3), false))
         {
            // another instance of the application must be running so exit
            return;
         }
         // Put code to run the application here
      }
   }
}

So in the above code we create a mutex with a unique key (“some_unique_application_key”). It’s best to use something like a URL and application name, so maybe “putridparrot.com\MyApp” as an example. The mutex is held onto for the life of the application for obvious reasons.

Next we try to WaitOne, we need a timeout on this otherwise we’ll just block at this point until the other instance closes down (or more specifically the Mutex on the other instance is released). So choose a time span of your choice. If the timeout occurs then false is returned from WaitOne and we can take it that another instance of the application is running, so we exit this instance of the application.

On the other hand if (within the timeout) WaitOne returns true then no other instance of the application (well more specifically the named Mutex) exists and we can go ahead and do whatever we need to run our application.

Semaphore & SemaphoreSlim

Basically a Semaphore allows us to set the initial count and the maximum number of threads than can enter a critical section.

The standard analogy of how a Semaphore works is the nightclub and bouncer analogy. So a nightclub has a capacity of X and the bouncer stops any clubbers entering once the nightclub reaches it’s capacity. Those clubbers can only enter when somebody leaves the nightclub.

In the case of a Semaphore we use WaitOne (or Wait on SemaphoreSlim) to act as the “bouncer” to the critical section and Release to inform the “bouncer” that a thread has left the critical section. For example

private readonly Semaphore semaphore = new Semaphore(3, 3);

private void MyCriticalSection(object o)
{
    sempahore.WaitOne();
    // do something
    semaphore.Release();
}

In the code above, say our calling method creates 20 threads all running the MyCriticalSection code, i.e.

for (int i = 0; i < 20; i++)
{
   Thread thread = new Thread(Run);
   thread.Start();
}

What happens is that the first three threads to arrive at semaphore.WaitOne will be allowed access to the code between the WaitOne and Release. All other threads block until one or more threads calls release. Thus ensuring that at any one time a maximum of (in this case) 3 threads can have access to the critical section.

Okay but the Semaphore allows an initial count (the first argument) so what’s that about ?

So let’s assume instead we have an initial count of 0, what happens then ?

private readonly Semaphore semaphore = new Semaphore(0, 3);

The above code still says we have a maximum of 3 threads allowed in our critical section, but it’s basically reserved 3 threads (maximum threads – initial count = reserved). In essence this is like saying the calling thread called WaitOne three times. The point being that when we fire off our 20 threads none will gain access to the critical section as all slots are reserved. So we would need to Release some slots before the blocked threads would be allowed into the critical section.

Obviously this is useful if we wanted to start a bunch of threads but we weren’t ready for the critical section to be entered yet.

However we can also set the initial count to another number, so let’s say we set it to 1 and maximum is still 3, now we have a capacity of 3 threads for our critical section but currently only one is allowed to enter the section until the reserved slots are released.

Note: It’s important to be sure that you only release the same number of times that you WaitOne or in the case of reserved slots you can only release up to the number of reserved slots.

To put it more simply, think reference counting. If you WaitOne you must call Release once and only once for each WaitOne. In the case of where we reserved 3 slots you can call Release(3) (or release less than 3) but you cannot release 4 as this would cause a SemaphoreFullException.

Important: Unlike a Mutex or Monitor/lock a Semaphore does not have thread affinity, in other words we can call Release from any thread, not just the thread which called WaitOne.

SemaphoreSlim

SemaphoreSlim, as the name suggests in a lightweight implementation of a Semaphore. The first thing to notice is that it uses Wait instead of WaitOne. The real purpose of the SemaphoreSlim is to supply a faster Semaphore (typically a Semaphore might take 1 ms per WaitOne and per Release, the SemaphoreSlim takes a quarter of this time, source ).

See also

Semaphore and SemaphoreSlim
Overview of Synchronization Primitives

and the brilliant Threading in C#

Puppet Task – TaskCompletionSource

Occasionally we will either want to wrap some code in a Task to allow us to use async await and maybe creating an actual Task is not required. It could be legacy code, for example maybe we’re running a threadpool thread and want to make this appear as a async await capable method or maybe we are mocking a method in our unit tests.

In such cases we can use the TaskCompletionSource.

Let’s look at a slightly convoluted example. We have a third party (or binary only) library with a ExternalMethod class and a method called CalculateMeanAsync which uses the threadpool to execute some process and when the process is completed it calls the supplied callback Action passing a double value as a result. So it’s method signature might look like

public static void CalculateMeanValueAsync(Action<double> callback)

Now we want to use this method in a more async await style i.e. we’d like to call the method like this

double d = await CalculateMeanValueAsync();

We want to basically create a task to handle this but we want to manually control it from outside of the external method. We can thus use the TaskCompletedSource as a puppet task, writing something like the code below to wrap the external method call in an async await compatible piece of code.

public Task<double> CalculateMeanValueAsync()
{
   var tcs = new TaskCompletionSource<double>();

   ExternalMethod.CalculateMeanValueAsync(result => 
   {
      tcs.SetResult(result);
   });

   return tcs.Task;
}

What happens here is we create a TaskCompletionSource, and return a Task from it (which obviously may or may not return prior to the ExternalMethod.CalculateMeanValueAsync completion. Our calling code awaits our new CalculateMeanValueAsync method and when the callback Action is called we set the result using tcs.SetResult. This will now cause our TaskCompletionSource task to complete allows our code to continue to any code after the await in the calling method.

So we’ve essentially made a method appear as a Task style async method but controlling the flow via the TaskCompletionSource.

Another example might be in unit testing. When mocking an interface which returns a Task we could create a TaskCompletionSource and create a setup that returns it’s Task property, then set the mock result on the TaskCompletionSource. An example of such a test is listed below:

[Fact]
public async Task CalculateMean_ExpectCallToIStatisticCalculator_ResultShouldBeSuppliedByMock()
{
   TaskCompletionSource<double> tc = new TaskCompletionSource<double>();

   var mock = new Mock<IStatisticsCalculator>();
   mock.Setup(s => s.CalculateMeanAsync()).Returns(tc.Task);

   tc.SetResult(123.45);

   Calculator c = new Calculator(mock.Object);
   double mean = await c.CalculateMeanAsync();
   Assert.Equal(123.45, mean);

   mock.Verify();
}

So in this example we have a Calculator class which takes an IStatisticsCalculator (maybe it allows us to swap in and out different code for the calculations – I didn’t say it was a perfect example). Now in our test we want to create a mock (I’m using xUnit and Moq for this). We expect the Calculator to call the mock code and return the result from it.

As you can see the mock sets up the Task and then we set the result on the TaskCompletionSource to emulate a completion of the task.

Note: In this example you must return Task on your async test method or you may find the test passing even when it clearly shouldn’t