Playing with Shaders: Creating a water effect

Lately I’ve been looking at a really cool project on Codeplex for Pixel Shaders. The set of shaders in this library is awsome and really easy to use in you application….

All you need to do to consume any Shader is add a reference to the WPFShaderEffectLibrary class library and you can start using the shaders in XAML.What is really important is that you install the Shaders Build Task before trying to build the shader library (if you just add a reference to the ready build dlls you don’t even need to do this).

 

Water

So let’s have a look at how we can use shaders to simulate water on screen.

This is very easy all we need is a ripple shader effect. so something like this

   1: <Window.Resources>

   2:  

   3:    <Storyboard x:Key="waterAnimMain">

   4:        <DoubleAnimation Storyboard.TargetName="rippleMain" Storyboard.TargetProperty="Phase" To="0" From="10" Duration="0:0:2.0"  FillBehavior="Stop" />

   5:        <DoubleAnimation Storyboard.TargetName="rippleMain" Storyboard.TargetProperty="Amplitude" To="0" From="0.6" Duration="0:0:2.0"  FillBehavior="HoldEnd" />

   6:        <DoubleAnimation Storyboard.TargetName="rippleMain" Storyboard.TargetProperty="Frequency" To="0" From="30" Duration="0:0:2.5" FillBehavior="HoldEnd" />

   7:    </Storyboard>

   8:  

   9: </Window.Resources>

  10: <Grid Background="Transparent" >

  11:  

  12:    <Border>

  13:        <Border.Background>

  14:            <LinearGradientBrush EndPoint="0.93,0.925" StartPoint="0.094,0.125">

  15:                <GradientStop Color="#FF272788" Offset="0.112"/>

  16:                <GradientStop Color="#FF090916" Offset="0.721"/>

  17:                <GradientStop Color="#FE222267" Offset="0.28"/>

  18:                <GradientStop Color="#FE131339" Offset="0.453"/>

  19:                <GradientStop Color="#FF04040A" Offset="0.974"/>

  20:            </LinearGradientBrush>

  21:        </Border.Background>

  22:    

  23:    </Border>

  24:  

  25: </Grid>

  26:  

  27: <Window.Effect>

  28:    <shader:RippleEffect Amplitude="0" Frequency="0" Phase="0" x:Name="rippleMain"  />

  29: </Window.Effect>

This is our Shader

   1: <shader:RippleEffect Amplitude="0" Frequency="0" Phase="0" x:Name="rippleMain"  />

And we animate this shader like so to make the effect of water

   1: <Storyboard x:Key="waterAnimMain">

   2:      <DoubleAnimation Storyboard.TargetName="rippleMain" Storyboard.TargetProperty="Phase" To="0" From="10" Duration="0:0:2.0"  FillBehavior="Stop" />

   3:      <DoubleAnimation Storyboard.TargetName="rippleMain" Storyboard.TargetProperty="Amplitude" To="0" From="0.6" Duration="0:0:2.0"  FillBehavior="HoldEnd" />

   4:      <DoubleAnimation Storyboard.TargetName="rippleMain" Storyboard.TargetProperty="Frequency" To="0" From="30" Duration="0:0:2.5" FillBehavior="HoldEnd" />

   5:  </Storyboard>

We invoke this animation by having a DispatcherTimer trigger the animation every now and then and changing the Center property of the Shader to a random point from 0 to 1.

This already gets us very close but it still does not feel like real water. The trick is to animate to ripple effects at the same time. This will make the ripple effects expand together and thus making the control which has the shader applied look like water. Yet the problem is that you can only apply ONE shader per control. BUT you can have another shader on the parent control and that would still apply the shader on all children (I explain this in this article).

   1: <Window.Resources>

   2:  

   3:     <Storyboard x:Key="waterAnimMain">

   4:         <DoubleAnimation Storyboard.TargetName="rippleMain" Storyboard.TargetProperty="Phase" To="0" From="10" Duration="0:0:2.0"  FillBehavior="Stop" />

   5:         <DoubleAnimation Storyboard.TargetName="rippleMain" Storyboard.TargetProperty="Amplitude" To="0" From="0.6" Duration="0:0:2.0"  FillBehavior="HoldEnd" />

   6:         <DoubleAnimation Storyboard.TargetName="rippleMain" Storyboard.TargetProperty="Frequency" To="0" From="30" Duration="0:0:2.5" FillBehavior="HoldEnd" />

   7:     </Storyboard>

   8:  

   9:     <Storyboard x:Key="waterAnimSub">

  10:         <DoubleAnimation Storyboard.TargetName="rippleSub" Storyboard.TargetProperty="Phase" To="0" From="10" Duration="0:0:2.0"  FillBehavior="Stop" />

  11:         <DoubleAnimation Storyboard.TargetName="rippleSub" Storyboard.TargetProperty="Amplitude" To="0" From="0.6" Duration="0:0:2.0"  FillBehavior="HoldEnd" />

  12:         <DoubleAnimation Storyboard.TargetName="rippleSub" Storyboard.TargetProperty="Frequency" To="0" From="30" Duration="0:0:2.5" FillBehavior="HoldEnd" />

  13:     </Storyboard>

  14:  

  15: </Window.Resources>

  16: <Grid Background="Transparent" >

  17:  

  18:     <Border>

  19:         <Border.Background>

  20:             <LinearGradientBrush EndPoint="0.93,0.925" StartPoint="0.094,0.125">

  21:                 <GradientStop Color="#FF272788" Offset="0.112"/>

  22:                 <GradientStop Color="#FF090916" Offset="0.721"/>

  23:                 <GradientStop Color="#FE222267" Offset="0.28"/>

  24:                 <GradientStop Color="#FE131339" Offset="0.453"/>

  25:                 <GradientStop Color="#FF04040A" Offset="0.974"/>

  26:             </LinearGradientBrush>

  27:         </Border.Background>

  28:         <Border.Effect>

  29:             <shader:RippleEffect Amplitude="0" Frequency="0" Phase="0" x:Name="ripple" Center="{Binding ElementName=main, Path=(local:MouseBehaviour.LastMouseUp)}" />

  30:         </Border.Effect>

  31:     </Border>

  32:  

  33:     <Grid.Triggers>

  34:  

  35:         <EventTrigger RoutedEvent="UIElement.MouseUp">

  36:             <BeginStoryboard Storyboard="{StaticResource waterAnim}"/>

  37:             <BeginStoryboard Storyboard="{StaticResource waterAnimMain}"/>

  38:         </EventTrigger>

  39:     </Grid.Triggers>

  40:  

  41:     <Grid.Effect>

  42:         <shader:RippleEffect Amplitude="0" Frequency="0" Phase="0" x:Name="rippleSub"  />

  43:     </Grid.Effect>

  44:  

  45: </Grid>

  46:  

  47: <Window.Effect>

  48:     <shader:RippleEffect Amplitude="0" Frequency="0" Phase="0" x:Name="rippleMain"  />

  49: </Window.Effect>

And that’s it. Now we have a perfect water look thanks to the Codeplex Pixel Shader library :)

I created a sample app that shows all this. The app also has another feature so that you can touch the water by using the mouse and the water would ripple from the point you touch (of course this is with Behaviours so that you can even reuse it :D )

Happy coding :D

DOWNLOAD SOURCE CODE

Mediator v2 for MVVM WPF and Silverlight applications

This last 2 weeks, us WPF Disciples have been talking a lot about the Mediator pattern for MVVM applications. Me and Josh Smith revised my previous Mediator implementation and found some problems with it.

Problem: There was a memory leak. Once a Mediator subscribes for one or more messages it would be kept in memory since the Mediator was holding a reference to the ViewModel.
Solution: We could have just exposed an unregister method so that when you call this method the Mediator would release the instance of the ViewModel. But sometimes it is hard to know when a ViewModel is going to die… So we went a step further and created the WeakAction. The WeakAction stores the instance of the ViewModel in a WeakRefence thus the ViewModel can be garbage collected without any problem and once it does get garbage collected the Mediator automatically removes that ViewModel registration from the list.

While we were at it we PIMPED the Mediator API :) We added 2 approaches to subscribe to the Mediator and we also added support for (thanks to David Anson suggestion) strongly typed parameters.

So now the Mediator offers 2 methods of registration, a declarative way of registering and an imperative way as well.

The Declarative approach. (Supported in WPF and Silverlight)

This approach uses attributes so that you can decorate the messages that act as subscribers for messages.Here is an example

   1: /// <summary>

   2: /// Subscribe to Message1

   3: /// </summary>

   4: /// <param name="message">The message to be passed</param>

   5: [MediatorMessageSink(MediatorMessages.Message1, ParameterType = typeof(SomeData))]

   6: public void Test(SomeData data)

   7: {

   8:     MessageBox.Show(data.Text + "\nReceived by: ColleagueA");

   9: }

So you just have to decorate your method with MediatorMessageSink attribute and the Method will get invoked every time a message is broadcasted via the Mediator.

As you can see the Mediator also supports strongly typed parameters. In order to do so you have to specify the ParameterType property on the attribute as shown in the sample code above. You can pass 0 or 1 parameters. If you don’t have any parameters just ignore the ParameterType (since this is an named Property and you can just not set it )

When using the declarative approach you must register the instance of the ViewModel to the Mediator. This is just one line of code in the ViewModel constructor. Here is how you do that

   1: public ColleagueA()

   2: {

   3:     //Register all decorated methods to the Mediator

   4:     Mediator.Register(this);

   5: }

This will inspect all methods of the ViewModel and look for the MediatorMessageSink attribute and register the appropriate methods to the Mediator. If you are going to have a base class for the ViewModels in your project and you can put this in the constructor of your base class. As simple an that.

 

The Imperative approach. (Supported in WPF ONLY)

If you do not want to use the attribute based registration we offer an imperative approach where you specify a method to be registered to a specific message. This implementation is exactly as it was in the old Mediator yet now it supports strongly typed parameters.

Here is how you can use this in your code

   1: public ColleagueC()

   2: {

   3:     //Register a specific delegate to the Mediator

   4:     Mediator.Register(MediatorMessages.Message1,

   5:         (Action<SomeData>)

   6:         delegate(SomeData x) 

   7:         {

   8:             Test = x.Text;

   9:             MessageBox.Show(x.Text + " \nReceived by: ColleagueC"); 

  10:         });

  11: }

This method is supported in WPF only since in Silverlight you cannot call an anonymous method (via reflection). If you try to use this method in Silverlight you will get an InvalidOperationException saying “This method is not supported in Silverlight”.

 

Conclusion

I packaged the Mediator in a class library so that you can go ahead and add a reference and reuse this library in your day to day projects.As always feedback is much appreciated.

Download MediatorLib + Sample application

[MVVM + Mediator + ACB = cool WPF App] – Intro

Finally I managed to spare some time and build a WPF sample application to showcase the use of MVVM + Mediator and also how AttachedCommandBehaviours can be used to further reduce (or better eliminate) C# code in XAML code behind files. I am also using one of my favorite WPF libraries FluidKit. In the app I create my own 3D transition for the FluidKit TransitionPresenter (I will be posting a whole post on this).

I will be posting at least 4 posts

- MVVM

- MVVM and the Mediator pattern

- FluidKit CoverFlow and FluidKit TransitionPresenter

- Using AttachedCommandBehaviours

Here are some teaser screenshots of the application in action :)

Screen1 Screen2

Screen3 Screen4

 

Setup of application environment

This application uses a SQL Database so you will need an instance of SqlServer 2005 running (you can use SqlServer Express).

I packaged the database as a backup so all you need to do is restore the database from the SqlServer Management Studio Express (this is your easiest option). If you don’t have this I suggest you download it, it’s free.

To restore the database file (WPFDisciplesDB.bak) follow these steps

- First of all download the database file from here.

- Right click on the Databases folder in the SQL Server Management Studio Express and select Restore database

Step 1

This will open a dialog for you. In the Restore Database dialog enter a name for the database in the “To database” text field > Select “From device” radio button and browse for the WPFDisciples.bak that you downloaded. The file will appear in the list. Tick the checkbox (which is un checked by default) and press ok.

Step 2 

Now that we have our database set up all we need to do is specify in the app.config the connection string of the new database and we are done.

Stayed tuned because this should be real fun :)

aaaa I nearly forgot… The data in the database is not the full version… I will add more projects from the mighty WPF Disciples as time goes by…. Will continue updating the download link here (and put a comment or something to show you that I updated the db version)

Download Full Source Code from HERE

Just in case you missed it, here is a copy of the database

XBAPs Part 2: Consuming WCF services from an XBAP

Introduction

One of the big improvements to XBAPs in .NET 3.5 is the ability to consume WCF services. Nowadays Service Oriented Architectures (SOAs) are very popular and used almost everywhere. This all makes sense, as SOA is very scalable, and for many cases it is the best approach to take for a project; so why not enable SOA for XBAPs as well. To tell you the truth, you could consume WCF services from XBAP in .NET 3.0, yet the XBAP had to have Full Trust, and not Partial Trust, which usually spells trouble. Anyway we don’t have to worry much about this now because .NET 3.5 enables XBAPs to consume WCF services even in Partial Trust. Read more about this and it’s limitations here.

Setting up our workspace

Ok so let’s start by creating a simple WCF service. Open Visual Studio and create a WCF service by clicking File > New > Project and then select Web > WCF Service application

NewWCF

I am not going to cover the basics of how to create a WCF service, yet by default the WCF Service Visual Studio template creates a simple service for us already (called IService). So yes, if you hit F5 and run the service you will already have a service up and running. Once we have our simple service let’s create a Simple XBAP in the same solution (in order to do this please refer to my previous post).

Now that we have both the WCF service and the XBAP how are we going to make them communicate? Well, thanks to Visual Studio this is super simple. All you have to do is Right click the XBAP project, select the “Add Service Reference” option and a Dialog will pop up:

AddServiceReference

Please Note: If you do not run the service you will get an error while expanding the Tree nodes of the service in this Dialog. If the service is not running Visual Studio cannot get the Metadata of the service, since this is just another EndPoint of the service. In order to run the service just Right Click on Service1.svc and select View in Browser.

Ok, now that we added the Service Reference, Visual Studio will go to work and generate a Proxy class for us. We will use this proxy class to communicate with the WCF service. By default the Proxy class is called <Name of service>Client so in our case it will be called Service1Client. This proxy class will have a method for every OperationContract we have in our service. You can also choose to create an Async version of the service. In order to do so just right click the Service1 (in the XBAP project that got created when we added the Service Reference) and select Configure Service Reference.

ChangeTheServiceToHaveASYNC

In this dialog check the Generate Async operations checkbox and Visual Studio will add an async version of the OperationContracts for you (Thank you VS… we love you :) )

The first error you’ll see

Ok now that we have everything set up lets do a simple button in our XBAP and in the Click event handler call a method. Something like this….

   1: private void Button_Click(object sender, RoutedEventArgs e)
   2: {
   3:     Service1Client client = new Service1Client();
   4:     MessageBox.Show(client.GetData(1));
   5: }

Let’s hit F5 and run our XBAP and see what happens.

AND BAMMMM a big ugly exception is thown.

InvalidOperationException

The WSHttpBinding with name WSHttpBinding failed validation because it contains a BindingElement with type System.ServiceModel.Channels.SymmetricSecurityBindingElement which is not supported in partial trust

which in VS looks like this

WCFError

Yet I promised you guys that WCF is supported in Partial trust XBAPs…. And it is, it’s just that the default WCF EndPoint is not :) By default a WCF Service has it’s EndPoint set up as WsHTTPBinding which is not supported in Partial trust XBAPs. In order to fix this Right click the app.config of your service and select “Edit WCF Configuration” (if this option is not available go to Tools > WCF Service Configuration Editor then select open and specify the path of your App.config. Once you have the app.config opened in the editor Expand the Bindings Node and select the node under that. Open the Security tab and choose None as security level.

ChangeSecurityLevelOfBinding

Once that’s done run the app again.

The Second error you’ll see

And this time it’s a SecurityException saying

Request for the permission of type ‘System.Net.WebPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089′ failed.

SecondError

In order to fix this Go to the XBAP project Properties and select Debug tab. Select the Start External Program option and enter the following exe path “C:\WINDOWS\System32\PresentationHost.exe” and in the Command Line arguments text field enter the following

-debug <Path of XBAP> –debugSecurityZoneUrl <URL of service>

in my case it was

-debug “D:\net resources\My Blog\XBAPAndWCF\XBAPClient\bin\Debug\XBAPClient.xbap” -debugSecurityZoneUrl http://localhost:53265/Service1.svc

[Update]

Thanks to Mark Smith I discovered a new an easier way of doing this. All you have to do is

1) Open XBAP project properties

2) Select Security tab

3) Advanced button

4) Check “Grant application access to site of origin” (should be checked already)

5) Type in the URL into the textbox where the web service is running

Security

We have to do this so that we set up an envirorment for the XBAP just like it is running from the same URL of the service.

Conclusion

And there you have it. Now you should be armed and ready to start doing XBAPs that consume WCF service.

Download sample application

XBAPs Part 1: An introduction to this Gem

Introduction

XBAP XBAPs (XAML Browser Application) are a really cool feature that was introduced in .NET 3.0 together with WPF. Well you can say that XBAPs are as such part of WPF because at the end of the day XBAPs are just WPF applications that can run inside the browser. One important thing to state here is that XBAPs and Silverlight have nothing to do with each other. XBAPs are full .NET enabled WPF applications, while Silverlight is a “cut down version of WPF” that runs as a browser plugin. In order to run a Silverlight enabled website you need to download the Silverlight installer(that is really really small approx 4.3 MB), if you want a client to run a XBAP the client has to have .NET installed on his machine (the Full .NET or Client Profile).

Before we continue I would like to point out that this post is just an introduction to XBAPs. I will have Part 2, Part 3 and Part x that should be much more interesting to follow…. Yet if you never heard of XBAPs you should continue reading this post (and try not to fall asleep :P).

What does your Client need?

As I said above, in order for a client to run your XBAP he/she needs to have .NET framework installed. It’s as if the client is going to run a Windows application. XBAPs got a set of improvements in .NET 3.5 such as support for Firefox (read more here) and also support for consuming WCF service in partial trust mode (with some limitations of course but still it’s good, read more here). So yea if you are planning on using XBAP’s I would seriously consider .NET 3.5.

To summarize your Client needs to have .NET installed and he can use the XBAP in Internet Explorer or if he prefers (and you are using .NET 3.5) Firefox.

Some things to keep in mind …

XBAPs run in the browser and give an impression of being a normal website (super cool website I must say :P) while instead they are just actual apps that never jump out of the browser, yet there is more to it… XBAP’s run in a “sandbox”, basically they run as Partial Trust by default. What this means is that some of the things that you would assume would work in a WPF app would not work in an XBAP, for example Reflection (and also the new 3.5 SP1 feature Effects :( ). Of course there are workarounds. You can run XBAPs as Full trust mode and we will discuss how to later on in this article.

Building a simple XBAP

So let’s start having a look at how one can build an XBAP. In order to create a new XBAP project you have to do the usual stuff, so go to File > New > Project and select WPF Browser Application

Step1

Now that we created the project, let’s have a look at what Visual Studio created for us

Step2

So as you can see by default Visual Studio created more or less the same stuff it would have created for a WPF Application yet instead of using a Window it created a Page. This is very important because a Page was designed for Navigation (the back and forward button of the browser). I will discuss Navigation more later on in this article. Besides this Visual Studio also created a pfx file. The pfx file is a way how to sign the exe, by default Visual Studio creates a pfx file that it uses to sign the Click once installer for the XBAP.

Signing

The image above shows how Visual Studio generated that pfx file. Please not that there is the Computer name and username inside the pfx files (which obviously is not something you want to give to your client). Charles Perzold discusses this in more detail here.

Ok so now that we know what Visual Studio created for us (thanks VS we love you) we can test our XBAP app (yea we can already run it :) ). In order to see something on screen lets just create a button in the Page1.xaml and press F5 to run.

   1: <Button Content="My First XBAP :) " Height="50" Width="150"/>

FirstApp

Yahhooo we have everything figured out don’t we :) well there are a couple of other things we need to have a look at.

Conclusion

If you are a WPF developer you will be developing XBAP in no time. There are a couple of things you must keep in mind, like Code Access Security and other tricks like how to consume WCF service…. In my next posts I will cover these things and make sure that I pass on my knowledge (knowledge that came from a lot of frustration and hours of head banging on the table)

Using the WPF Web browser control in a ToolTip

While writing a small app that I will be publishing here, I stumbled upon a strange issue. I was trying to put the WPF WebBrowser control inside a Tooltip yet the WebBrowser was not appearing on the screen. After an hour of debugging and trying out different things I found this WPF Forum thread that solved my issue… The problem has something to do with the WebBrowser being a native control and not a pure WPF control (so you are actually using an HwndHost in order to show it in a WPF app).  Also you might want to have a look at this blog post, it’s from the answerer of the forum post. Anyway, I just thought to share this with who ever is encountering this problem…..

Now I’m headed back coding my new project… should be cool, will post it shortly hopefully :)

.NET Client Profile + WPF = Superb Apps

For those of you that have been asking where is Marlon? “Why did he stop blogging for these past 3 weeks?”
Well I’ve been really really busy packaging 2 new hot products. I currently work at Uniblue Systems where we develop system utilities that help you keep you PC healthy and clean. I have been working at Uniblue for 2 years but never in these 2 years I was excited as I am today. We released our first 2 products using WPF, packaged with .NET Framework Client Profile.

.NET Framework Client Profile is really superb, it enables us at Uniblue to distribute our products to the end user in a fast and easy way. Before .NET Client Profile, it was very hard for companies such as Uniblue to ship software with .NET Framework because the download of the framework alone is massive. Our customers hate to wait ( don’t yours? ). With .NET Client Profile the download + installation is really fast and that’s why our customers love it!

Client Profile not only installs the basic .NET Framework components, but it installs .NET 3.5 SP1 (Client Only) which means you get all the WPF goodness + all new super stuff that .NET 3.5 SP1 provides. So yea we can also go crazy with user interfaces!  If you want to check out one of our new products (developed fully with WPF) check it out here …. please submit as many feedback as possible… I can’t wait to see what you think ….

 

SUMP 

Visual Studio 2008 + .Net 3.5 SP1 is out now

I’ve been counting the seconds for this to happen… It is finally here, Visual Studio 2008 SP1 and .Net 3.5 SP1 is out now. Get it from here.

Before installing this I would suggest that you have a look at this post. Quote from here “When installing Visual Studio 2008 Sp1 Beta1, you may encounter an error that you must first remove KB944899 before setup can continue. This message can be displayed if you have installed any KB for Visual Studio 2008, not just KB944899.”

There could be some issue if you had the SP1 Beta installed so better to have a look instead of crying like a baby after :D

Do read the Read me file!!!!! It is very important… I had a problem with the following but thanks to the readme file I knew what to do

2.1.9 Windows Automatic Update notification appears during Visual Studio 2008 SP1 installation on Windows Vista

Windows Automatic Update notification to restart the computer may appear when Visual Studio 2008 SP1 is being installed on a Windows Vista computer that does not have .NET Framework 2.0 SP2 and .NET Framework 3.0 SP2 installed. Allowing Windows Update to restart immediately will cause Visual Studio Setup to fail.

To resolve this issue:

Postpone the restart until Visual Studio SP1 installation is finished.

 

And yes it does take a long time, so be patient… it’s worth every second :D

success

 

Have a nice evening with the brand new SP1… I love you Microsoft…. I LOVE YOU

My wish came true…. I can now use DataBinding in a ConverterParameter

WARNING: This solution uses reflection so it cannot be used in XBAP or applications running with Partial Trust.

One of the things I hear often in forums and also lately on the WPF Disciples mailing list is, “How come I cannot use binding in ConverterParameters?” or “My personal pet peeve is the ConverterParameter. Ah if I could only bind it to something in my ViewModel!!”

So let’s start by seeing why you cannot use binding for a ConverterParameter. The simple answer to that would be, a ConverterParameter is not a DependencyProperty thus you cannot use Binding. Yet the following question would be, WHY isn’t it a DependencyProperty?? Well there are a few things we must have a look at here. First of all the Binding class is not a DependencyObject. Secondly the BindingBase class seals itself when the binding activates, this means that once the Binding is activated you cannot change any properties. If you try to do so you get a nice InvalidOperationException saying “Binding cannot be changed after it has been used”.

Yet, the WPF platform is very flexible so I decided to start digging into it and see what I can come up with (obviously always consulting the WPF KING OF KINGS, Dr.WPF).

The first idea…

My first idea was to create a MarkupExtension that spits out an instance of an object that has a Dependency Property that you can bind with (some sort of Proxy that can update the Binding and specify a new value). So your XAML would look like this

{Binding ElementName=checkbox1, Path=IsChecked, Converter={StaticResource conv}, ConverterParameter={code:BindableParameter {Binding ElementName=checkbox2, Path=IsChecked}} }

Yet this failed miserably because of a simple yet hard problem in the design I had. You cannot get the BindingExpression of that binding because the BindingExpression is not constructed yet. I could get the Binding instance but the Binding instance alone is nothing without the BindingExpression since you can update a binding by calling the UpdateSource method of the Binding expression.

Back to the drawing boards…. and finally the Solution

So let’s have a look at what we want to achieve. We want to

1. Let the User Specify a Binding for a ConverterParameter somewhere in the XAML
2. Make sure that when a value of the ConverterParameter changes the original Binding gets updated.

In order to solve problem 1, I decided to go to my best friend, AttachedProperties. Basically the idea is that you set an attached property that specifies the value of a ConverterParameter of a specific binding. So the XAML would look something like this

   1: <ToggleButton Content="I am bound to the checkbox" x:Name="toggle"
   2:      code:BindableParameter.BindParameter="{code:BindableParameter ToggleButton.IsChecked, Binding={Binding ElementName=checkbox2, Path=IsChecked}}"
   3:      IsChecked="{Binding Converter={StaticResource conv}, ElementName=checkbox1, Path=IsChecked}"/>

In the attached property you specify what Binding you want to target by supplying the DependencyProperty to which the original Binding is applied. In this case the original Binding is for the IsChecked property of the ToggleButton. Then you can simple specify the Binding you want for the ConverterParameter by setting the Binding property of the BindableParameter markup extension.

Now that you have supplied this information, the BindableParameter can do some tricks for you. Basically once you specify the BindParameter attached property the BindableParameter will get a BindingExpression for the original binding and make sure to set the ConverterParameter when ever needed. Have a look at the PropertyChanged event handler of the BindParameter Attached property.

   1: private static void OnBindParameterChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
   2: {
   3:     FrameworkElement element = d as FrameworkElement;
   4:     if (element == null)
   5:         throw new InvalidOperationException("BindableParameter can be applied to a FrameworkElement only");
   6:
   7:     BindableParameter parameter = (BindableParameter)e.NewValue;
   8:     element.Initialized += delegate
   9:     {
  10:         parameter.TargetExpression = BindingOperations.GetBindingExpression(element, parameter.TargetProperty);
  11:         parameter.TargetBinding = BindingOperations.GetBinding(element, parameter.TargetProperty);
  12:
  13:         //update the converter parameter 
  14:         InvalidateBinding(parameter);
  15:     };
  16: }

As you can see, in the above code, all we are doing is get the instance of the BindingExpression and storing it in an instance variable(TargetExpression). Same goes for the Binding, storing it in the TargetBinding. Now that we have all this information we can do Step 2 (Make sure that when a value of the ConverterParameter changes the original Binding gets updated)

In the Property Changed event handler of the Binding we must force the BindingExpression to update and change the value of the converter parameter. This can be done quite easily one would say but there are 2 main problems.

Problem 1. How to make the binding work for the BindableParamater?? The BindableParameter is not in the LogicalTree because it is just a DependencyObject thus the Binding that you set will not be valid. In order to overcome this issue we can do a little trick with the Freezable class. If we make the BindableParameter inherit from the Freezable it gets the inheritance context thus Binding is now valid. For more info on this technique visit Dr. WPF blog

Problem 2. How can we change the value of ConverterParameter if the Binding is sealed (remember? the Binding class will throw an InvalidOperationException if we try to change a property of the Binding). This problem required me to do some hard core disassembling of the Binding class and I found out that each Property Setter of the Binding class has a call to a method CheckSealed. This method looks like this

   1: internal void CheckSealed()
   2: {
   3:     if (this._isSealed)
   4:     {
   5:         throw new InvalidOperationException(SR.Get("ChangeSealedBinding"));
   6:     }
   7: }
   8:

So what we must do is to get the _isSealed Field info by reflection and change it’s value to false, then change the ConverterParameter and finally put the _isSealed value back to true so that WPF does not notice us playing tricks on him :)
Once we do that we are free to change the value of the ConverterParameter and we can Refresh the Binding

Something like this

   1: private static void InvalidateBinding(BindableParameter param)
   2: {
   3:     if (param.TargetBinding != null && param.TargetExpression != null)
   4:     {
   5:         //this is a hack to trick the WPF platform in thining that the binding is not sealed yet and then change the value of the converter parameter
   6:         bool isSealed = (bool)isSealedFieldInfo.GetValue(param.TargetBinding);
   7:
   8:         if (isSealed)//change the is sealed value
   9:             isSealedFieldInfo.SetValue(param.TargetBinding, false);
  10:
  11:         param.TargetBinding.ConverterParameter = param.ConverterParameterValue;
  12:
  13:         if (isSealed)//put the is sealed value back as it was...
  14:             isSealedFieldInfo.SetValue(param.TargetBinding, true);
  15:
  16:         //force an update to the binding
  17:         param.TargetExpression.UpdateTarget();
  18:     }
  19: }

And there it is …. I can now use binding for a ConverterParameter and the XAML looks like this

   1: <Window.Resources>
   2:    <code:DummyConverter x:Key="conv"/>
   3: </Window.Resources>
   4: <StackPanel>
   5:    <CheckBox x:Name="checkbox2" Content="I am the parameter for the converter"/>
   6:    <CheckBox x:Name="checkbox1" Content="I am bound directly"/>
   7:
   8:    <ToggleButton Content="I am bound to the checkbox" x:Name="toggle"
   9:                  code:BindableParameter.BindParameter="{code:BindableParameter ToggleButton.IsChecked, Binding={Binding ElementName=checkbox2, Path=IsChecked}}"
  10:                  IsChecked="{Binding Converter={StaticResource conv}, ElementName=checkbox1, Path=IsChecked}"/>
  11: </StackPanel>

Hope you enjoy this …..

DOWNLOAD SOURCE CODE

kick it on DotNetKicks.com

NameScope, my name is Marlon you know….

Introduction

Did you ever wonder why you can have the same name registered for different parts of your XAML? Here is an example (notice the name “border” in different parts of the XAML)

   1: <ContentControl Content="Hello world" x:Name="border">
   2:     <ContentControl.ContentTemplate>
   3:         <DataTemplate>
   4:             <Border BorderBrush="Silver" BorderThickness="1" CornerRadius="5" Margin="20" x:Name="border">
   5:                 <StackPanel>
   6:                     <TextBlock Text="I am a DataTemplate" HorizontalAlignment="Center"/>
   7:                     <ContentPresenter Content="{Binding}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
   8:                 </StackPanel>
   9:             </Border>
  10:         </DataTemplate>
  11:     </ContentControl.ContentTemplate>
  12:
  13:     <ContentControl.Template>
  14:         <ControlTemplate TargetType="ContentControl">
  15:             <Border BorderBrush="Silver" BorderThickness="1" CornerRadius="5" x:Name="border" >
  16:                 <StackPanel>
  17:                     <TextBlock Text="I am a ControlTemplate" HorizontalAlignment="Center"/>
  18:                     <ContentPresenter />
  19:                 </StackPanel>
  20:             </Border>
  21:         </ControlTemplate>
  22:     </ContentControl.Template>
  23: </ContentControl>

As you can see the XAML above border is registered 3 times. This is possible because of WPF Namescopes. Basically the Window(that I am using to put the ContentControl in) has it’s own NameScope the DataTemplate also has it’s own and also the ControlTemplate (some actually implement the INameScope interface themselves).

Namescopes are a very important concept that one must understand. Why? Let me give you an example.

   1: <StackPanel>
   2:     <ContentControl Content="Hello world" x:Name="border">
   3:         <ContentControl.ContentTemplate>
   4:             <DataTemplate>
   5:                 <Border BorderBrush="Silver" BorderThickness="1" CornerRadius="5" Margin="20" x:Name="border">
   6:                     <StackPanel>
   7:                         <TextBlock Text="I am a DataTemplate" HorizontalAlignment="Center"/>
   8:                     <ContentPresenter Content="{Binding}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
   9:                     <CheckBox x:Name="checkbox" Content="Checkbox here" />
  10:                 </StackPanel>
  11:                 </Border>
  12:             </DataTemplate>
  13:         </ContentControl.ContentTemplate>
  14:     </ContentControl>
  15:
  16:     <ToggleButton Content="Toggle button bound to checkbox" IsChecked="{Binding ElementName=checkbox, Path=IsChecked}"/>
  17: </StackPanel>

The XAML above has a ContentControl that has a ContentTemplate with a CheckBox and a Toggle button that is trying to bind to that checkbox. The binding is using ElementName to try to find the checkbox yet that will NOT be successful because the “checkbox” is registered in a different NameScope (remember a DataTemplate has it’s own NameScope!)

Namescope and Animations

Another scenario where NameScopes are heavily used are animation. When you create a Storyboard you specify a Storyboard.TargetName attached property to specify which element you want to animate. Something like this….

   1: <Window.Resources>
   2:     <Storyboard x:Key="animation" >
   3:         <DoubleAnimation To="50" AutoReverse="True" RepeatBehavior="Forever"
   4:                        Storyboard.TargetName="button"  Storyboard.TargetProperty="Height"/>
   5:     </Storyboard>
   6: </Window.Resources>
   7:
   8: <Window.Triggers>
   9:     <EventTrigger RoutedEvent="FrameworkElement.Loaded">
  10:         <BeginStoryboard Storyboard="{StaticResource animation}"/>
  11:     </EventTrigger>
  12: </Window.Triggers>
  13:
  14: <StackPanel>
  15:     <ContentControl Content="Hello world" x:Name="border">
  16:         <ContentControl.ContentTemplate>
  17:             <DataTemplate>
  18:                 <Border BorderBrush="Silver" BorderThickness="1" CornerRadius="5" Margin="20" x:Name="border">
  19:                     <StackPanel>
  20:                         <TextBlock Text="I am a DataTemplate" HorizontalAlignment="Center"/>
  21:                     <ContentPresenter Content="{Binding}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
  22:                     <CheckBox x:Name="checkbox" Content="Checkbox here" />
  23:                 </StackPanel>
  24:                 </Border>
  25:             </DataTemplate>
  26:         </ContentControl.ContentTemplate>
  27:     </ContentControl>
  28:
  29:     <ToggleButton Content="Toggle button bound to checkbox" Height="25" x:Name="button"/>
  30: </StackPanel>

The above code would execute as expected, the ToggleButton named “button” would start animating it’s height when the window is Loaded. But what if you want to animate something in the DataTemplate? If you try to create a Storyboard in the Resources section of the window to animate the Checkbox  named “checkbox” you would get an InvalidOperationException saying ‘checkbox’ name cannot be found in the name scope of ‘NamescopeExample.Window1′. This is because the checkbox lives in a different NameScope from the storyboard. One thing you can do is to move the Storyboard in the DataTemplate.Resources so that the storyboard would be created in the same Namescope of the checkbox. Something like this

   1: <DataTemplate>
   2:     <DataTemplate.Resources>
   3:         <Storyboard x:Key="checkboxAnimation" RepeatBehavior="Forever">
   4:             <ColorAnimation To="Red" AutoReverse="True"
   5:                 Storyboard.TargetName="checkbox" Storyboard.TargetProperty="(Control.Background).(SolidColorBrush.Color)"/>
   6:         </Storyboard>
   7:     </DataTemplate.Resources>
   8:     <Border BorderBrush="Silver" BorderThickness="1" CornerRadius="5" Margin="20" x:Name="border">
   9:         <StackPanel>
  10:             <TextBlock Text="I am a DataTemplate" HorizontalAlignment="Center"/>
  11:         <ContentPresenter Content="{Binding}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
  12:         <CheckBox x:Name="checkbox" Content="Checkbox here" Background="Black" />
  13:     </StackPanel>
  14:     </Border>
  15:     <DataTemplate.Triggers>
  16:         <EventTrigger RoutedEvent="FrameworkElement.Loaded">
  17:             <BeginStoryboard Storyboard="{StaticResource checkboxAnimation}"/>
  18:         </EventTrigger>
  19:     </DataTemplate.Triggers>
  20: </DataTemplate>

Namescope and C# code

But what if you are creating elements in code… One would say out “Easy… Just set the name property” like so….

   1: ToggleButton button = new ToggleButton();
   2: button.Height = 25;
   3: button.Content = "Toggle Button";
   4: button.Name = "button";
   5: container.Children.Add(button);

No no no and NO…. This does not work! Setting the Name property of the control will not register that Control to the NameScope. So how to do it? Easy.. have a look

   1: ToggleButton button = new ToggleButton();
   2: button.Height = 25;
   3: button.Content = "Toggle Button";
   4: NameScope.GetNameScope(this).RegisterName("button", button);
   5: container.Children.Add(button);

All you have to do is, first find in which NameScope you want to register the element (in this case I want to add it to the Window NameScope), secondly register the element to that NameScope by using the RegisterName method of the INameScope interface.

You can even use the RegisterName method of the FrameworkElement. For example if I want to add a Button to a StackPanel, you can ask the StackPanel to register the name of the Button. In my case I could have done like this

   1: ToggleButton button = new ToggleButton();
   2: button.Height = 25;
   3: button.Content = "Toggle Button";
   4: container.RegisterName("button", button);
   5: container.Children.Add(button);

Some other tips and related articles…

If you have an element in the Resources section you will not be allowed to set a name for that element. One way of enabling that element with a name is by using the RegisterName method of the NameScope class as explained above (you might want to set the name for animations for example).

You might want to also implement your own NameScope by implementing the INameScope interface. I saw a very clever solution by doing such a thing, by WPF super hero Andrew Smith.

Josh Smith the WPF Rock star and his Element Spy is also a brilliant article that must be read..

kick it on DotNetKicks.com