Category Archives: Programming

NInject ChildKernel

I’ve been working on an application which is basically a glorified scheduler. Within it I have the concept of projects which are made up triggers, tasks etc. So we have a parent child relationship going on between the project and the child elements, the triggers etc.

One problem I came across was that the application holds a StandardKernel (as one might expect) and injects dependencies etc. into the projects, triggers and tasks but I wanted to use the same mechanism to allow me to inject the current instance of a project into the children, i.e. the triggers and tasks could (if they wanted) get access to the parent project instance.

Obviously if I add the project to the application wide kernel, all triggers and tasks would get a project object, but not necessarily the project which acts as their parent (actually it’d probably fail to allow me to resolve to multiple instances of a project anyway). Of course I could pass the instance of the project to each trigger or task at construction or explicitly calling the relevant method/property, but I wanted to reuse the NInject mechanisms so as to keep a standard way of injecting objects into this application.

Enter the ChildKernel. A Ninject extension class available via GitHub.

Using the ChildKernel we can create a new kernel, which (if you like) inherits the bindings from a parent kernel and then we add further bindings specific to it’s use, as per

ChildKernel child = new ChildKernel(kernel);
child.Bind<IProject>().ToMethod(_ => currentProject);

kernel would be our StandardKernel acting as the parent kernel.

Now we simply Get or Inject using this child kernel and if a dependency is not resolved using the child, it is passed to the parent kernel to resolve.

MemoryCache, caching in .NET 4

Having used the Enterprise Application Blocks in the past I’ve been well aware of the capabilities of the caching block, but recently was looking for some caching for a small application I have and stumbled across the MemoryCache which looks like it’s the replacement for the Caching Block.

It supports caching policy’s such as absolute expiration and sliding expiration.

You can create multiple instances of a MemoryCache or use a singleton in the form of MemoryCache.Default in the typical scenarios where only a single instance of the cache is required.

A simple example is shown below

MemoryCache cache = MemoryCache.Default;

cache.Add("Key", "Value", new DateTimeOffset(DateTime.Now.AddSeconds(10));
object o = cache.Get("Key");

In the above (fairly useless) example we get the default instance of the cache and then add a key and value to the cache with an absolutely expiry in 10 seconds time. We then get the item from the cache and ten seconds later it will have been removed from the cache.

When I get around to it I’ll amend with some better examples.

Beware of using RegexOptions.Compiled Regex in some situations

Using the RegexOptions.Compiled option in a Regex instance means that the regular expression is compiled into IL upon creation, which sounds good.

But beware, it can be an expensive operation which highlights itself if the code is called many times. If the Regex instance is reused a lot it makes sense to use this option, but even then beware that the time to create the compiled expression might not be worth it in a one-off scenario. In such cases do not use RegexOptions.Compiled.

Let’s look at some results of a simple test.

In the first example I’m simple creating the Regex in a method and calling the Split method on it, so these results obviously include the creation and use of the object. “Option” denotes whether the Regex was compiled or interpreted and the number column denotes is the number iterations calling we make creating a Regex and using it (time is shown in ms)

[table “” not found /]

Next we’ll create the Regex and reuse it

[table “” not found /]

Obviously what you see in the second table is that when the Regex Split is called a low number of times the performance gain of compiling the expression is minimal, but it gets progressively better the more times the regex is used.

So the lesson is to not use the RegexOptions.Compiled option unless you’re pretty sure the performance hit of creating the Regex isn’t an issue and it will be called a large number of times. All other times do not used RegexOptions.Compiled.

Note: performance tests were carried out on a 32-bit Windows XP machine

The WPF ListView

By default a ListView looks and acts much like a standard WPF ListBox (when in it’s default state) but ofcourse we can also include headers/columns and groupings whichon top of the basic list of data.

Let’s assume we’re wanting to display a collection of Person objects where the Person type is made up of FirstName, LastName and Age. For this example assume these are exposed by the People property on our view model.

To display our collection we can simply do the following

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

But this will display the type name for each item in our collection and ofcourse doesn’t have headings. So to add headings we need to use the following

<ListView ItemsSource="{Binding People}">
   <ListView.View>
      <GridView>
         <GridViewColumn Header="First Name" Width="150" 
                   DisplayMemberBinding="{Binding FirstName}"/>
         <GridViewColumn Header="Last Name" Width="150" 
                   DisplayMemberBinding="{Binding LastName}"/>
         <GridViewColumn Header="Age" Width="100" 
                   DisplayMemberBinding="{Binding Age}"/>
      </GridView>
   </ListView.View>
</ListView>

this will also display the members we’re binding to so no longer display the type name.

So far so good, but to add groupings we need to do a little more work. In XAML we have the following (in the Window ResourceDictionary)

<CollectionViewSource Source="{Binding People}" x:Key="GroupedItems">
   <CollectionViewSource.GroupDescriptions>
      <PropertyGroupDescription PropertyName="LastName" />
   </CollectionViewSource.GroupDescriptions>
</CollectionViewSource>

If using the above XAML we also need to alter the ListView’s ItemSource to this

<ListView ItemsSource="{Binding Source={StaticResource GroupedItems}}">

this will then bind to the GroupedItems. Note we must use the “Source=” XAML.

We can also easily declare the same groupings in C# code as per below

CollectionView collectionView = 
      (CollectionView)CollectionViewSource.GetDefaultView(list.ItemsSource);
PropertyGroupDescription pgd = new PropertyGroupDescription("LastName");
collectionView.GroupDescriptions.Add(pgd);

Note: in the above case our ListView has the x:Name=”list” and ofcourse doesn’t require the ItemsSource binding change listed for the XAML code.

Using the CollectionView we add property group descriptions but we need to amend our ListView XAML to use this. By adding the ListView.GroupStyle as per below, we create the control template for the groupings

<ListView.GroupStyle>
   <GroupStyle>
      <GroupStyle.ContainerStyle>
         <Style TargetType="GroupItem">
            <Setter Property="Template">
               <Setter.Value>
                  <ControlTemplate TargetType="{x:Type GroupItem}">
                     <StackPanel>
                        <TextBlock FontWeight="Bold" 
                                FontSize="14" Text="{Binding Path=Name}"/>
                        <ItemsPresenter/>
                     </StackPanel>
                  </ControlTemplate>
               </Setter.Value>
            </Setter>
         </Style>
      </GroupStyle.ContainerStyle>
   </GroupStyle>
</ListView.GroupStyle>

The key things to note in the above XAML are that we need to ensure we put the ItemsPresenter into the ControlTemplate or now items are displayed and we do not bind to the data but instead bind to the CollectionViewGroup which is what the CollectionViewSource groups the data into. So in this case Name represents the string data for the grouping name and we could also bind to ItemCount for example if we wanted to show to the user the number of items in the grouping.

Friend assemblies (or how to make internals visible to other assemblies)

As you know, the internal modifier denotes that types and type members are only accessible by code from the same assembly.

Therefore the DoSomething method in the following is not visible to other assemblies but can be using by code within the assembly which contains this type

public class MyClass
{
   internal int DoSomething()
   {
   }
}

In some cases it’s useful to have internal types or type members visible to other assemblies, but limited to only those assemblies. These assemblies are known as friend assemblies.

To denote the friend assemblies we add the InternalsVisibleTo attribute to the assembly who hosts the internals and specify the friend assembly in the following manner

[assembly: InternalsVisibleTo("FriendAssembly")]

Now the FriendAssembly can access the DoSomething method on type MyClass.

Dynamically resolve assemblies at runtime

I came across this recently. I must admit I’ve not personally had a need for it, but it’s an interesting “trick”, so I wrote a little reusable framework around it.

So let’s say you deploy an application without all of it’s dependencies as part of the expected dependency resolution path. For example, in this case I’ve embedded all the assemblies as resources into the EXE so I can deploy a single file, but the technique should allow us to also resolve the dependencies via some other technique, such as from a remote location.

Create an EXE application and add the DLL(s) or EXE(s) and optionally their PDB(s) to the application as embedded resources. As your application depends on one (or more) of these assemblies then one (or more) of them will also be referenced. Mark the referenced assemblies which you’ve embedded as Copy Local=false (obviously we’re not talking about the GAC assemblies here) so they’re not copied to the output folder, obvious if you run the application now it will fail to locate these required assembles as we’ve embedded them as resources.

So, when the application starts up it attempts to resolve any missing dependencies and if it has any problem resolving the dependencies it fires the AssemblyResolve event on the AppDomain.CurrentDomain, it’s at this point that we want to dynamically load the assemblies ourselves into the app domain.

What we need to do is attach an event handler to the AppDomain.CurrentDomain.AssemblyResolve, as per

AppDomain.CurrentDomain.AssemblyResolve +=
       DynamicAssemblyResolver.Resolve(args, new ResourceAssemblyResolver());

I now try to resolve the missing dependency using an IAssemblyResolver (in this instance that is the ResourceAssemblyResolver class).

Below is a helper class named DynamicAssemblyResolver which simple (potentially) loops through any supplied IAssemblyResolver implementations passing the AssemblyName that we’re trying to resolve

public class DynamicAssemblyResolver
{
   public static Assembly Resolve(ResolveEventArgs e, 
            IAssemblyResolver resolver, params IAssemblyResolver[] alternateResolvers)
   {
      return Resolve(e.Name, resolver, alternateResolvers);
   }

   public static Assembly Resolve(string nameToResolve, 
            IAssemblyResolver resolver, params IAssemblyResolver[] alternateResolvers)
   {
      return Resolve(new AssemblyName(nameToResolve), resolver, alternateResolvers);
   }

   public static Assembly Resolve(AssemblyName assemblyToResolve, 
            IAssemblyResolver resolver, params IAssemblyResolver[] alternateResolvers)
   {
      Assembly assembly = resolver.Resolve(assemblyToResolve.Name);
      if (assembly != null)
      {
         return assembly;
      }

      if (alternateResolvers != null)
      {
         foreach (IAssemblyResolver alternateResolver in alternateResolvers)
         {
            assembly = alternateResolver.Resolve(assemblyToResolve.Name);
            if (assembly != null)
            {
               return assembly;
            }
         }
      }
      return null;
   }
}

The interface for a resolver class looks like this

public interface IAssemblyResolver
{
   Assembly Resolve(string assemblyName);
}

and finally the implementation that resolves dependencies using the files embedded within the resource looks like

public class ResourceAssemblyResolver : IAssemblyResolver
{
   public Assembly Resolve(string assemblyName)
   {
      Assembly executingAssembly = Assembly.GetExecutingAssembly();
      return (from name in executingAssembly.GetManifestResourceNames() 
		where name.Contains(assemblyName) 
		select Resolve(executingAssembly, name)).FirstOrDefault();
   }

   private static Assembly Resolve(Assembly executingAssembly, string assemblyName)
   {
      try
      {
         using(Stream manifestResourceStream = 
                      executingAssembly.GetManifestResourceStream(assemblyName))
         {
            if (manifestResourceStream == null)
   	    {
               return null;
            }

            string pdb = Path.ChangeExtension(assemblyName, ".pdb");
	    using (Stream pdbResourceStream =                
                     executingAssembly.GetManifestResourceStream(pdb))
	    {
	       return Assembly.Load(Read(manifestResourceStream),
			(pdbResourceStream != null) ?
			Read(pdbResourceStream) : null, 								                
                        SecurityContextSource.CurrentAppDomain);
 	    }
         }
      }
      catch (Exception)
      {
         throw;
      }
   }

   private static byte[] Read(Stream stream)
   {
      byte[] array = new byte[stream.Length];
      stream.Read(array, 0, array.Length);
      return array;
   }
}

The above code tries to match the supplied assembly name with the resources found embedded in the calling assembly.

Note: A failing of the above approach is that if more than one file exists with the same name, i.e. MyLib.dll existing in multiple resources but in different folders (obviously), then the first one only is ever resolved.

A simple lookless control in WPF

One of the key design principles for designing controls in WPF is the separation of UI from the actual control implementation (or functionality if you prefer). The aim is to create a control with properties, methods, events, states etc. as needed that does not rely on the specifics of the way the UI displays the control.

I’m going to work through a very simple lookless control to just get an idea how such a control might be implemented.

What’s the control going to be ?

Okay I don’t want anything too large as this is mean’t as a quick and easy to follow post. So the control will be a countdown timer control. A control which takes a time, in seconds and each second decreases the count until it reaches zero at which point it stops.

The control will have the following properties

From – this will hold to countdown “from” value (in seconds). In other words the value we start the countdown at.
Current – this will hold the current value in the countdown, obviously this will reduce from the “From” value down to zero.
IsRunning – this will allow us to know if the countdown timer is running.

Steps

  1. Create a CountdownControl class and implement the properties described above
  2. Create a CountdownControl XAML file and create a default style
  3. Create an alternate UI by overriding the ControlTemplate

Let’s implement this thing

Step 1

So step 1 is to create a new class called CountdownControl, we will derive this from a Control as we’re not looking to extend any existing control for this. So it should look like

public class CountdownControl : Control
{
}

Nothing exciting there.

As we’re going to countdown from a given value and for this example we’ve assumed the use of seconds only. We’ll use the DispatcherTimer to give us an event every second which will allow us to decrement the current value accordingly. As this isn’t mean’t to be a step by step for coding this I’ll simply point out that we can use the snippets in Visual Studio 2012 (dp and dpp) to create the propeties as follows.

  1. Create the IsRunning as a dependency property with property changed event
  2. Create the CurrentProperty as a readonly dependency property
  3. Create the From as a dependency property with property changed event
  4. Create a CountdownControl constructor and add the code to created the timer
  5. create the timer tick event and have it decrement the Current property until it reaches 0 then set the IsRunning to false
  6. On the OnIsRunningRunningChanged either start or stop the timer depending on the value passed to it
  7. On the OnFromChanged, set the IsRunning to true if a value greater than 0 is assigned to the From property

And here’s the code

public class CountdownControl : Control
{
   private readonly DispatcherTimer timer;

   public CountdownControl()
   {
      timer = new DispatcherTimer();
      timer.Interval = TimeSpan.FromSeconds(1);
      timer.Tick += TimerTick;
   }

   private void TimerTick(object sender, EventArgs e)
   {
      if (Current > 0)
      {
         SetValue(CurrentPropertyKey, Current - 1);
         if (Current == 0)
         {
            IsRunning = false;
         }
      }
   }

   public static readonly DependencyProperty IsRunningProperty =
		DependencyProperty.Register("IsRunning", typeof(bool), 
                typeof(CountdownControl),
		new FrameworkPropertyMetadata((bool)false,
		new PropertyChangedCallback(OnIsRunningChanged)));

   public bool IsRunning
   {
      get { return (bool)GetValue(IsRunningProperty); }
      set { SetValue(IsRunningProperty, value); }
   }

   private static void OnIsRunningChanged(DependencyObject d, 
               DependencyPropertyChangedEventArgs e)
   {
      CountdownControl target = (CountdownControl)d;
      bool oldIsRunning = (bool)e.OldValue;
      bool newIsRunning = target.IsRunning;
      target.OnIsRunningChanged(oldIsRunning, newIsRunning);
   }

   protected virtual void OnIsRunningChanged(bool oldIsRunning, bool newIsRunning)
   {
      if (!DesignerProperties.GetIsInDesignMode(this))
      {
         if (newIsRunning)
            timer.Start();
         else
            timer.Stop();
      }
   }

   private static readonly DependencyPropertyKey CurrentPropertyKey
		= DependencyProperty.RegisterReadOnly("Current", typeof(int), 
                        typeof(CountdownControl),
			new FrameworkPropertyMetadata((int)0));

   public static readonly DependencyProperty CurrentProperty
		= CurrentPropertyKey.DependencyProperty;

   public int Current
   {
      get { return (int)GetValue(CurrentProperty); }
   }

   public static readonly DependencyProperty FromProperty =
		DependencyProperty.Register("From", typeof(int), typeof(CountdownControl),
		new FrameworkPropertyMetadata((int)0,
		new PropertyChangedCallback(OnFromChanged)));

   public int From
   {
      get { return (int)GetValue(FromProperty); }
      set { SetValue(FromProperty, value); }
   }

   private static void OnFromChanged(DependencyObject d, 
                 DependencyPropertyChangedEventArgs e)
   {
      CountdownControl target = (CountdownControl)d;
      int oldFrom = (int)e.OldValue;
      int newFrom = target.From;
      target.OnFromChanged(oldFrom, newFrom);
   }

   protected virtual void OnFromChanged(int oldFrom, int newFrom)
   {
      SetValue(CurrentPropertyKey, newFrom); 
      IsRunning = (newFrom > 0);
   }
}

As can be seen, there’s no UI code here, only properties and functionality yet this will implement a countdown clock.

Note: The user of the DesignerProperties.GetIsInDesignMode is to stop the control counting down when in the XAML designer

Before we move onto the next step, which is to add a default style/look, let’s finish up here by creating the following static constructor

static CountdownControl()
{
   DefaultStyleKeyProperty.OverrideMetadata(typeof(CountdownControl), 
		new FrameworkPropertyMetadata(typeof(CountdownControl)));
}

As per a previous post on extending an existing control, the DefaultStyleKeyProperty is here to change the metadata for this class to associate a new style with this specific type.

Step 2

Create a ResourceDictionary named CountdownControl.xaml and add the following code

<Style TargetType="{x:Type Controls:CountdownControl}">
   <Setter Property="Template">
      <Setter.Value>
         <ControlTemplate TargetType="{x:Type Controls:CountdownControl}">
            <Grid>
               <TextBlock Text="{Binding Current, RelativeSource={RelativeSource TemplatedParent}}" />
            </Grid>
         </ControlTemplate>
      </Setter.Value>
   </Setter>
</Style>

There’s not masses to say here except that this will now display the Current property value as it counts down in a TextBlock. The use of the binding instead of TemplateBinding is covered in a previous post, but basically TemplateBinding is lightweight and does not support the type conversion from an int (the current property) to a string. So we have to use the more verbose Binding syntax to solve this.

Lastly, if you are creating this control in it’s own assembly and haven’t already got one, create a Themes folder in your project and add a Generic.xaml ResourceDictionary inside the folder. Then add the following XAML

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

Step 3

Now we can use the CountdownControl by simply adding the following

<Controls:CountdownControl From="30"/>

Note: This assumes you’ve a namespace for the CountdownControls aliased as Controls.

If you run the application now it should display a simple text countdown from 30 to zero.

So whilst our lookless code then got a default look, we now want to re-template it to something a little nicer (although still fairly simple).

We’re going to now re-template the control to use a progress bar to show the countdown. So let’s see the new Style for this.

<Style TargetType="{x:Type c:CountdownControl}">
   <Setter Property="Template">
      <Setter.Value>
          <ControlTemplate TargetType="{x:Type c:CountdownControl}">
             <Grid>
                <ProgressBar Minimum="0" Maximum="{Binding From, RelativeSource={RelativeSource TemplatedParent}}" 
                      Value="{Binding Current, RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay}" Height="20"/>
             </Grid>
          </ControlTemplate>
       </Setter.Value>
    </Setter>
</Style>

As you can see we’re now also using the From property as well as the Current property. We might have also decided to use the IsRunning with a BooleanToVisibilityConverter to hide the progress bar when it reaches zero.

In Summary

We’ve created a control which began by having no UI and was lookless and also very much testable. We then created a basic default look so we could at least see something when designing with the control. Finally we created a nicer UI for our specific needs.

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.