WPF Resources

Resources in WPF terms, are simply mechanisms for storing data, whether it be strings, colours, brushes, styles etc.

We can store such resources locally, within the scope of a Window or control or we can store the resources globally within the Application resources.

Resources are stored as key value pairs within a Resources section or ResourceDictionary. We therefore need to define a x:Key for each item in the resources, for example

<Window.Resources>
   <system:Int32 x:Key="ButtonWidth">100</system:Int32>
</Window.Resources>

In the above XAML we’re storing an Int32 type in the resource of a Window class. The key is “ButtonWidth” and the value is “100”.

Now let’s look at some example of using the resources.

<Window x:Class="Test.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <FontWeight x:Key="Weight">Black</FontWeight>
    </Window.Resources>    
    <Grid>
        <Button Content="Hello World" FontWeight="{StaticResource Weight}" />
    </Grid>
</Window>

In the XAML above we are storing the resources within the scope of the Window. This means everything within the Window class will now have access to these resources but they’re not available outside of this Window.

We’ve created a FontWeight type resource with the key “Weight”. In the Button we use the resource to assign the value from the key “Weight” to the FontWeight of the Button. simply think of the key as a variable name.

Note: I’ll discuss the StaticResource at the end of this post

We can add resources to a top level UserControl (for example) just as we’ve done in the Window example, but we can also add resources to controls within a control or Window, for example, let’s take the Button from the above example but move the resource into the Button.Resources

<Button Content="Hello World">
   <Button.Resources>
      <FontWeight x:Key="Weight">Black</FontWeight>
   </Button.Resources>
   <Button.FontWeight>
      <Binding Source="{StaticResource Weight}"/> 
   </Button.FontWeight>
</Button>

Notice in the code above, we’ve used the Button.FontWeight element instead the FontWeight attribute of the Button (as per the original code). This is simply because when we add the resources in this way, these are now within the scope of the Button and unfortunately this means we cannot apply to the Button attributes themselves.

Application resources are defined in much the same way as for a Window resources but are available to all Windows/controls – in other words have global scope. We might declare our resource as follows

<Application x:Class="Test.App"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   StartupUri="MainWindow.xaml">
   <Application.Resources>
      <FontWeight x:Key="Weight">Black</FontWeight>
   </Application.Resources>
</Application>

Finally we can also create XAML files which are of type ResourceDictionary

<ResourceDictionary
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">  
   <FontWeight x:Key="Weight">Black</FontWeight>
</ResourceDictionary>

Now to use this ResourceDictionary from our Window (or control) we need to writing the following

<Window.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="MyResources.xaml"></ResourceDictionary>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Window.Resources> 

This will merge the MyResources.xaml into the Windows ResourceDictionary and thus make the FontWeight resource available to the Window as if we’d declared it within the Window Resources. However by using the ResourceDictionary, not only can we create tidier code, removing possibly lots of resources from our views but also create libraries of resources that can be easily reused.

Resource Markup Extension

In the code above, we used the StaticResource markup extension. This is not the only option for binding to resources. We could also use the DynamicResource markup extension.

The use of StaticResource means that resource is resolved once at the point the XAML is loaded. Whereas DynamicResource allows us to in essence, late bind, to the resource. This means we can write XAML which might have a DynamicResource binding to a resource but the resource doesn’t need to exist until runtime. This option also allows the binding to update automatically if the resource changes. Hence if you want to bind to a resource which might change, then you can use a DynamicResource – this is obviously very useful when we’re dealing with the concept of themes.

And finally

In some cases we might want to use the resource in code. If we’re embedding the string for the key within the XAML, this means we’ll have to duplicate the string in code – duplication is not good. So instead we might prefer to store the string in source code to begin with and reference this in our XAML.

So let’s create a C# file named it whatever you like, I’m going to call mine’s Constants.cs

Now let’s just create the following static class

public static class Fonts
{
   public const string Weight = "Weight";
}

We can obviously use this “Weight” in our code, but in XAML we’re going to need to do the following change.

<!-- Original -->
<FontWeight x:Key="Weight">Black</FontWeight>

<!-- Becomes -->
<FontWeight x:Key="{x:Static local:Fonts.Weight}">Black</FontWeight>

How many methods in my classes ?

I won’t waste time on this post explaining why I had to do this, but I had to find the number of methods on a whole bunch of classes.

NDepend to the rescue. Using the CQLinq language I wrote

Application.Methods.Where(m => 
m.ParentType.Name == "ClassName1" ||
m.ParentType.Name == "ClassName2").
Count(m => !m.IsGeneratedByCompiler)

Now I’ll admit the list of classes was coded directly into the query, which is obviously no good for reusing the query, but this mean’t it was quick and easy to get the code up and running in no time at all – and thus get my answer.

How to reference an existing NuGet package from a new project

So the scenario is this…

I’ve created a solution, added my projects, added some NuGet packages and all’s good with the world. Then I need to add a new project and reference some NuGet packages which I’m already using.

What’s the best way to do this?

In the past I’d go to the “Manage NuGet Packages” on the references section of a project and add the package again. However here’s the problem with this solution – unless you specify a specific version (you’ll be doing this through the Package Manager Console), you may find a different version of a package installed into your solution, which has its obvious downsides.

What about referencing the assemblies you require directly, i.e. use Add Reference and browse for them? I don’t actually know (at this time) whether this causes problems for NuGet with updates etc. but it’s not a great way when a package requires multiple assemblies, which make up a package.

What we really want is a way to say, reuse this package (already downloads and installed in the solution file system) in my new project.

The solution is simple, but I never noticed it before (how embarrassing)

One of the projects I’m working on has NuGet packages hosted in-house and they change often (hey its continuous deployment, that’s cool). So when I create a new project, all I want to do is get NuGet to somehow reference my existing package(s) and have NuGet handle all the references etc.

Well it’s actually all there, built into NuGet/Visual Studio.

  • Select the solution in solution explorer
  • Right mouse click and select Manage NuGet Packages for solution…
  • Select Installed packages
  • Locate the package that’s already installed
  • Click the Manager button
  • Now simply locate your new project and tick the checkbox next
  • Click OK, sit back and relax

Intercepting and creating SOAP messages using Fiddler

The title of this post is specific to a requirement I have which is part of a security audit which requires that I test the role based security on some of our servers.

I need to intercept SOAP messages from one of the .NET client applications I maintain and then change data within the message to try to impersonate other users to see whether the server code correctly allows/disallows user access via it’s role based security.

Obviously, if you know Fiddler (now from Telerik) you’ll know that we can intercept any network traffic between the machine we’re using and some server – we’re just going to touch on some of the very basics of using Fiddler.

Setting things up

So continuing down the path of the requirements I have. The first thing I need to do (prior to starting the client application) is to run Fiddler. I’m currently using Fiddler 4.4.9.9.

You may notice calls to the web or the likes over HTTP in the left hand pane of Fiddler. This is where we’ll see individual calls to our server(s). But before we can run our client application we need to ensure it uses Fiddler – so in my case I need to add/change the system.net section of the .NET application configuration file to look like the following

<system.net>
   <defaultProxy>
      <proxy bypassonlocal="false" usesystemdefault="true" />
   </defaultProxy>
</system.net> 

Now the client will use Fiddler as the proxy.

See Configure .NET Applications for more information of this subject

Okay, at this point we can run our .NET client and we should start seeing calls to any servers appearing within the left hand pane of Fiddler (obviously when they’re made via the client).

Once the application started I used Fiddler’s “Any process” button (a gun sight style icon on the toolbar) to select the .NET application so to reduce the traffic I would see in Fiddler.

Capturing a message

We’re not going to dive too deep into Fiddler for this post, but instead we’ll just look at how to use Fiddler to carry out the specifics of the requirements outlined at the start of this post.

Next up we’re going to make the client application do some task – in my case we’re using a read/write role so I can get a message that is valid for a user with these permissions.

So now I run the functionality on the client which will result in a server call and generate the SOAP message I want to capture. It should appear in the left hand pane of Fiddler. If we double click on the specific entry on the left hand pane the right hand pane of Fiddler will show us the Inspectors view. From here we can look at the SOAP message using various viewers.

Now switch to the RAW view of the bottom part of the Inspectors pane and press the View in Notepad. At this point I delete the HTTP header and am left with the raw message (in my case starting with <?xml to the end of the document).

Okay, we’ve captured the SOAP message, the next step is to change information within the SOAP message to impersonate a lower permission user. Obviously this depends on how you might pass the data for such user information, whether it’s within the header or envelope. Whether such information is plain text of encrypted.

Creating (or composing) a message

We’ve captured an existing message and changes the user details within the message. Now we’re going to use Fiddler to send the message to the server.

Select the Composer tab in the right hand pane of Fiddler. In my case I need to set the message to be a POST and I supply the full URL.

The top pane of this composer view will update with any response from the server and be default has the User-Agent set to Fiddler (obviously you can change this to suit).

In the request body we copy our previously captured and altered SOAP message and paste it into the request body section. Now simply press the Execute button at the top right of the Composer view and your request should be sent to the specified URL.

Obviously I had a very specific requirement for using Fiddler but ofcourse you might use it to simply capture various messages in whatever format you use and replaying them as part of a test suite or the likes.

.NET CLR Version Tool

I’d not come across this tool before, but whilst checking the location of the sn.exe tool I spotted it and thought I’d see what it did.

So the clrver.exe can be run from the Visual Studio command prompt or found at a location where your SDK exists, for example

"%ProgramFiles%\\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\clrver.exe"

Just running clrver.exe without any arguments will tell you which versions of the CLR are installed on your machine, whilst using the switch -all will result in a list of applications/processes running using the .NET CLR and tells us the version they’re using. If you already know the process id (pid) you can use clrver 123 to list the .NET CLR version being used by pid 123.

Observable.FromEventPattern discussed

I was actually looking through my past blog posts and noticed I’ve never published anything on Reactive Extensions (Rx). I actually have a draft “beginners” guide which I started a couple of years back, but never completed, so I may end up publishing that at a later date.

Note: The best resource for Rx information that I’ve found is Introduction to Rx, I’d definitely recommend you visit that site for complete and excellent documentation on Rx.

Okay, for this post I’m just going to focus on the FromEventPattern. Even though the syntax is pretty simple I have a habit of forgetting it everytime I come to use it, so as this blog is about refreshing my memory, I thought I’d write a blog post dedicated to this method.

Why use Rx instead of handling events in the conventional way?

One of the most obvious reasons to use Rx to handle events is that it can help stop those pesky memory leaks when we forget to unsubscribe to an event. Another reason is the IObservable returned from FromEventPattern is composable and we can filter events that we’re not interested in and/or marshal events from one thread onto another – for example when events are coming from a worker thread we might marshal them onto the UI thread.

Take a look at Observable.FromEventPattern Method to see the current syntax/overloads for this method.

I will not be covering all the overloads here but will instead look at the three I’ve used the most. So let’s get started…

FromEventPattern with an EventHandler which takes no EventArgs

In some cases you might have an event handler which doesn’t use EventArgs, for example

public event EventHandler Reverted;

in such a case we use the overload

public static IObservable<EventPattern<EventArgs>> FromEventPattern(
	Action<EventHandler> addHandler,
	Action<EventHandler> removeHandler)

So our code might look like this

var o = Observable.FromEventPattern(
   x => domainObject.Changed += x,
   x => domainObject.Changed -= x).
   Subscribe(_ => DoSomething());

FromEventPattern with standard event patterns (using the EventHandler class)

Building on the previous syntax…

In many cases, where the events that we want to subscribe to, use the “standard .NET event pattern”, (for example where the handler takes an EventArgs derived class) and were declared using the syntax

public event EventHandler<CellsInViewChangedEventArgs> CellsInViewChanged;

we will use this overload. Note: This version expects an EventHandler<> object.

public static IObservable<EventPattern<TEventArgs>> FromEventPattern<TEventArgs>(
	Action<EventHandler<TEventArgs>> addHandler,
	Action<EventHandler<TEventArgs>> removeHandler
)
where TEventArgs : EventArgs

To use this we simple supply the EventArgs derived type, for example

var o = Observable.FromEventPattern<CellsInViewChangedEventArgs>(
   x => grid.CellsInViewChanged += x,
   x => grid.CellsInViewChanged -= x).
   Subscribe(_ => DoSomething());

FromEvent pattern with standard event patterns (not using the Event Handler class)

Finally, for this post, in some cases we have events which do not use the EventHandler<> class, for example the WPF RoutedEvents use

public delegate void RoutedEventHandler(
   object sender, 
   System.Windows.RoutedEventArgs e)

In such cases we need to supply both the Delegate type and EventArgs type to the FromEventPattern, hence we use the syntax

public static IObservable<EventPattern<TEventArgs>> FromEventPattern<TDelegate, TEventArgs>(
	Action<TDelegate> addHandler,
	Action<TDelegate> removeHandler
)
where TEventArgs : EventArgs

our code will now look like this

var o = Observable.FromEventPattern<RoutedEventHandler, RoutedEventArgs>(
   x => button.Click += x,
   x => button.Click -= x).
   Subscribe(_ => DoSomething());

More…

I don’t intend to cover all the possible uses of the IObservable which is returned by the FromEventPattern, but suffice to say (as mentioned earlier). We can ensure events are marshaled onto the thread which created the observable, so for example if we create this from the UI thread we can write

var o = Observable.FromEventPattern<ValuesChangedEventArgs>(
   x => server.ValuesChanged += x,
   x => server.ValuesChanged -= x).
   ObserveOn(SynchronizationContext.Current).
   Subscribe(_ => DoSomething());

here, the ObserveOn will ensure that the events that might be coming from a worker thread are marshaled onto the current thread. Obviously if this was created on the UI thread this will marshal back onto that thread.

Creating awaitable types

If you’ve used async/await in your applications, you’ll generally await a Task, but you can actually make your own type awaitable. Let’s look at how we’d do this.

Why are Task’s awaitable?

A Task is awaitable, not because it’s a Task type, but its because it supports a specific method name which returns a TaskAwaiter or TaskAwaiter for the Task type. So let’s take a look at what this method looks like

public TaskAwaiter GetAwaiter()

So it’s really that simple, if we want to make our object awaitable we simply define the same method in our type.

What is a TaskAwaiter?

A TaskAwaiter is a struct which implements the ICriticalNotifyCompletion interface and the INotifyCompletion interface (the ICriticalNotifyCompletion derives from the INotifyCompletion). But this still wouldn’t make the TaskAwaiter awaitable it also needs the property IsCompleted and the method GetResult – more on this in “the rules for an “Awaiter” type” below.

It does seem strange that these methods weren’t all put into a single interface, but there you have it.

How do I create a bare minimum awaitable type?

Let’s first review the rules for making our type awaitable

  • Our type should have a method named GetAwaiter which takes no arguments and returns a suitable “Awaiter” type

and now the rules for an “Awaiter” type

  • The type should implement the INotifyCompletion interface or the ICriticalNotifyCompletion interface
  • It should have a IsCompleted property of type boolean
  • It should have a GetResult method which returns void or a result value
    • and now let’s put this together into a somewhat pointless type which demonstrates a bare minimum set of requirements to get this type to be awaitable

      public class MyObject
      {
         public MyAwaiter GetAwaiter()
         {
            return new MyAwaiter();
         }
      }
      
      public struct MyAwaiter
      {
         public void OnCompleted(Action continuation)
         {
            continuation();
         }
      
         public bool IsCompleted { get; private set; }
      
         public void GetResult()
         {			
         }
      }
      

      and now in use, we would have something like this

      var o = new MyObject();
      await o;
      

      Note: if you do not call the conitnuation() action in the OnCompleted method the code will block indefinitely.

      The flow of this code goes as follows…

      await o is called, this calls GetAwaiter on MyObject which returns a MyAwaiter. Next IsCompleted is checked, if the awaiter has already completed then control returns to the line after the await, if it’s false OnCompleted is called which basically blocks until the continuation is called, finally the GetResult method is called.

      Extension methods that are awaitable

      So we’ve discussed creating our own type, making it awaitable and even creating an awaiter type, but another approach which one might use is creating extension methods and instead of going to the hassle of creating an awaiter type, we’ll simply reuse the TaskCompletionSource type which can be used as a puppet task.

      Let’s go straight to some code which I’ve unashamedly lifted from Stephen Toub’s blog post await anything.

      public static TaskAwaiter<int> GetAwaiter(this Process process)
      {
         var tcs = new TaskCompletionSource<int>();
         process.EnableRaisingEvents = true;
         process.Exited += (s, e) => tcs.TrySetResult(process.ExitCode);
         if (process.HasExited)
         {
            tcs.TrySetResult(process.ExitCode);
         }
         return tcs.Task.GetAwaiter();
      }
      

      and we would use this as follows

      await Process.Start(“notepad.exe”)
      

      Looking at the extension method you can see we’re going to use the TaskCompletion classes GetAwaiter to return the awaiter type (in this case a TaskAwaiter) and we simply try to set the result on the TaskCompletionSource if, or when, the process exits.

      References

      await anything
      Design change: new “await” pattern for greater efficiency

Strange white on black numbers during debug in Visual Studio 2015

When running a Universal Windows application in debug mode within Visual Studio 2015 I noticed some “strange” white numbers on a black background adorning my application window (and in the case of a desktop application displayed on the top right of the screen).

It seems these are enabled via the App.xaml.cs file, within the OnLaunched method (the code in some cases may appear in the App() constructor according to the documentation) there’s the following code

#if DEBUG
   if(System.Diagnostics.Debugger.IsAttached)
   {
      this.DebugSettings.EnableFrameRateCounter = true;
   }
#endif

See also DebugSettings.EnableFrameRateCounter property.

As stated within the above link, this causes an overlay of two sets of numbers. Those in the upper left of the screen/Window relate to the application being debugged those in the upper right apply to the overall system.

Basically the left number is the app’s UI frame rate in frames per second and the right number is the CPU usage of the app’s UI thread per frame in milliseconds.

Getting started with Paket

For a while now I’ve been meaning to have a play with Paket and I’ve finally found some time to try it out.

What is Paket?

Paket is a package management tool along the lines of NuGet. In many ways you think of it as NuGet plus some extra goodies.

Like NuGet, you can download/update/install NuGet packages, but on top of that you have the ability to download/update/install files from GitHub or from the Gist repositories or single files from an HTTP resource. This is so useful, especially when you have files that maybe you don’t want to create assemblies around to reuse, but instead just want to include the files in your project in their minimal state, i.e. just as source code (or any other file type you like).

Jumping straight in

Okay, enough chat, let’s get started.

I’m going to create a solution in Visual Studio named PaketTest, mine’s a console application but it really doesn’t matter as we’re just going to walk through the quickest and simplest way to get up and running with Paket. We’re using this solution solely as a place holder so we can see our dependencies referenced and files loaded – to get a feel for how things work and look.

When the solution’s loaded we’re going to use NuGet to grab the paket.exe. The Paket website’s tutorial mentioned getting Paket EXE and/or the bootstrapper from GitHub, but in some scenarios you might be locked down by your companies download policy to not be able to download EXE’s. So either grab the bootstrapper and use that to download paket.exe or use NuGet to get it.

So follow these steps and we’ll be up and running in now time

  • From Package Manage Console in your Visual Studio solution, run Install-Package Paket
  • From a command prompt, navigate to the root folder of your solution
  • Create the directory .paket
  • You can either copy paket.exe to this location or run it from the packages folder, I’ve copied mine here as it’s an easier path to type each time
  • In the solution root folder create the file paket.dependencies. Next, add the following to that file
    source https://nuget.org/api/v2
    
    nuget Ninject
    
    github putridparrot/MusicTheory Theory.xml
    
    gist putridparrot/b3968f23bdabc86a6777 MemoryInformation.cs
    

    Obviously feel free to replace NInject and the putridparrot GitHub and Gist repositories/files with your own, but as I want to demo these three options, I know that there are files in those locations that we can download.

    The dependencies file is used to get the dependencies from the various locations but does not automatically add these to your solution, that’s covered in the next step.

  • Now we need to create another new file (again in the root folder of the solution) named paket.references. In here place the following code
    NInject
    
    File:Theory.xml
    File:MemoryInformation.cs
    

    This file is what Paket uses to actually add references and files to your solution. As you can see we’re basically saying we want to add the references NInject to our solution and the files listed (with the File: prefix) will be added to a paket-files solution folder. If you’d prefer the files are placed in the root folder or your solution, follow the file name with a . for example

    NInject
    
    File:Theory.xml .
    File:MemoryInformation.cs .
    

    Note: We can also specify a folder in our solution for any files, simply replace the . in the above examples with a folder name, for example

    NInject
    
    File:Theory.xml Data
    File:MemoryInformation.cs Source
    
  • Now we’ve got the configuration in place, run (from the command line in the root of the solution) .paket\paket.exe install.

    This will run the Paket application, which will read the .dependencies file and download the NuGet package NInject and the file Theory.xml from GitHub and the Gist file MemoryInformation.cs. It will then read the .references file (if one exists) to add the references for NInject and will add the two files Theory.xml and MemoryInformation.cs. Depending upon whether you used the . or not, the files will either be in the root of the solution or the paket-files solution folder or a folder you’ve specified.

What’s this paket.lock file

When you run the paket.exe install command you’ll notice a new file added to the root folder, named paket.lock. Mine looks like this

NUGET
  remote: https://nuget.org/api/v2
  specs:
    Ninject (3.2.2)
GITHUB
  remote: putridparrot/MusicTheory
  specs:
    Theory.xml (3383d5e239cf64fa8e65ada252fe08ae5764e36c)
GIST
  remote: putridparrot/b3968f23bdabc86a6777
  specs:
    MemoryInformation.cs (4368713d0b2c0c969be01e9309db818f67a65d53)

To quote “The paket.lock file”, this file “records the concrete dependency resolution of all direct and transitive dependencies of your project”. This file should be checked into your source repos. (along with the other two files) for other developers to use as it will ensure that the same versions of packages are loaded. i.e. if NInject (for example moves forward to version 4.0 this file ensures we’re all still on the same version).

Not covered in the above steps (mainly as I haven’t had need to use it so far), but you can also add a file via an HTTP resource to the dependencies using

http http://someurl/Myfile.cs

and then reference the file in the normal way in the references file, i.e.

File:MyFile.cs

Core paket commands

I’m going to cover some core paket commands here

paket.exe help

As you’d expect this will list all the currently available commands for paket and can be invoked using help or ? or a few other ways which you can find yourself by typing paket help.

paket.exe install

We’ve already covered this, but to document this, the install command is used to download the dependencies specified within the paket.dependencies file or the paket.lock file (remember if the paket.lock file is not supplied it will be generated via the install command).

paket.exe outdated

What if a dependency has a new version available ? We can run the outdated command to ask paket to report on whether any packages have been updated, i.e. are there any newer versions. This command does not actually update anything, it’s there to tell us if we might need to update.

packet.exe update

Unlike outdated, the update command will not only check for newer versions of packages but will download them and update any that are declared in the paket.references file.

paket.exe convert-from-nuget

If you’re working on a solution that is already using NuGet and you want to convert to paket you can use the convert-from-nuget command. See paket convert-from-nuget for a full list of steps/information on this command.

paket.exe restore

Previously I mentioned checking the paket.lock file into the source repos. Now if I’ve just joined a project and I need to restore the packages, I can run the restore command which works in a similar way to NuGet restore in that it will download the relevant packages and files based upon the information in the lock file and set my solution up accordingly. This command will use the .lock file to ensure it gets the same versions so I would now be in sync with those who checked this file in.

References

Paket on GitHub
The Paket website

Implementing a storyboard in code

So, I have a requirement to flash a cell (or row) in a XamDataGrid when an error occurs on the underlying model for the cell/row. I’m currently implementing this in code simply because I’ve inherited a new control from the XamDataGrid to handle all my requirements.

I won’t go into the full implementation of the style, but suffice to say the bit that matters looks like this

var style = new Style(typeof (CellValuePresenter));

var trigger = new DataTrigger
{
   Binding = new Binding("DataItem.IsValid"),
   Value = false
};

var animation = new BrushAnimation
{
   From = Brushes.LightPink,
   To = Brushes.Firebrick,
   Duration = TimeSpan.FromSeconds(0.2),
   AutoReverse = true
};

var storyboard = new Storyboard
{
   RepeatBehavior = RepeatBehavior.Forever
};

Storyboard.SetTargetProperty(animation, 
   new PropertyPath(BackgroundProperty));
storyboard.Children.Add(animation);

var enterBeginStoryboard = new BeginStoryboard
{
   Name = "flashingStoryboard",
   Storyboard = storyboard 
};

style.RegisterName("flashingStoryboard", enterBeginStoryboard);

trigger.EnterActions.Add(enterBeginStoryboard);
trigger.ExitActions.Add(
   new StopStoryboard 
   { 
      BeginStoryboardName = "flashingStoryboard" 
   });

style.Triggers.Add(trigger);

In the above code we obviously create the style, with the target type of the CellValuePresenter. Then we’re using a trigger to detect when the view model’s IsValid property is false. This will cause our flashing animation/storyboard to pulse the background brush from light pink to firebrick and back.

Note: The BrushAnimation object is taken from a stackoverflow post Brush to Brush Animation

The creation of the animation and storyboard, hopefully, are fairly self-explanatory. The idea is that when the trigger EnterActions is called the animation begins and when the ExitAction occurs the storyboard is stoppped. We need to supply a name to the StopStoryboard object and here’s where my first mistake was made.

The line style.RegisterName(“flashingStoryboard”, enterBeginStoryboard); is important. Without it we will find that the named storyboard is not found by the StopStoryboard object. The storyboard needs to have the name registered within the
style’s namescope otherwise you’ll get the error I encountered which is an InvalidOperation exception

‘flashingStoryboard’ name cannot be found in the name scope of ‘System.Windows.Style’

This exception will only occur when the StopStoryboard code is called as this is the point it needs to find the object from the namescope.