Making a generic UpdateSourceTrigger for PropertyChanged in Silverlight

In my previous post I explained how Silverlight 4 lacks the UpdateSourceTrigger for PropertyChanged. I focused on how you can overcome this issue for one of the biggest use cases, which is the TextBox.

In this post I will show how one can do this for any Dependency Property of any Framework element. Please note that this post is quite an experimental one. Probably the use case you are looking for is for the textbox scenario, if that is the case I would suggest that you use the more explicit approach i.e the one I show in my previous post. The take away from this post should be more the idea of how things work rather than the actual code I am using here, this code was never tested in production thus it might contain memory leaks and other issues.

The key for updating the binding when a property changes is to actually know when the property has changed and then force the binding to update the source. In WPF there are multiple ways of doing this, one of which is to use the DependencyPropertyDescriptor class. This class allows you to hook an event handler for when the specified property has changed. Unfortunately in Silverlight there is no DependencyPropertyDescriptor class thus one has to resort to some ninja trick Smile After doing some internet crawling I found an interesting approach using attached property creating and hooking to the property changed. The idea is that you create an attached property and you bind the newly created attached property to the property that is consuming the binding.

Let’s dig a bit deeper

Let’s say you have the following binding

<TextBox Text=”{Binding SomeText, Mode=TwoWay}”

The Text dependency property is consuming a binding and you want to update the source of the binding as soon as the property changes.

You create an attached property and you bind it to the Text property of that TextBox. This will get you notified when the text changes because when creating the attached property you can have a property changed handler. In the property changed handler you update the source of the binding.

You would create the attached property and the binding for notifications like so

// Create attached property

var listeningProperty = System.Windows.DependencyProperty.RegisterAttached(

    "ListenAttached" + propertyName,

    typeof(object),

    typeof(UpdateSourceTriggerProxy),

    new System.Windows.PropertyMetadata(OnPropertyChanged));


//Create a binding that will be updated when the property changes

var listeningBinding = new Binding(propertyName) { Source = element };

element.SetBinding(listeningProperty,

    listeningBinding);

Ok so I showed how you can workaround the lack of DependencyPropertyDescriptor in Silverlight for property changed notification, now how do we update the binding?

In order to do this we will need to get the instance of the Text Dependency Property. Unfortunately we will need to resort to reflection in order to get the instance of the Dependency property. We can do this by name

var propertyFieldInfo = frameworkElement.GetType().GetField(newPropertyName + "Property");

if (propertyFieldInfo == null)

    throw new InvalidOperationException(String.Format(

        "The property {0} does not exist in the element {1}. Make sure you specified the correct property.",

        newPropertyName, frameworkElement.GetType().FullName));

//Get the dependency property the binding is applied to

var property = (DependencyProperty)

    propertyFieldInfo.GetValue(frameworkElement);

As you can see I am attaching a string “Property” to the actual property name (in this case Text) when I try to get the dependency property by reflection. Even though in XAML you specify “Text” as the property name, the actual dependency property name is TextProperty (which is a coding standard for dependency properties), “Text” is how the property is registered to the framework.

So why did we need to get the actual instance of the Dependency property? We had to do this in order to get the Binding Expression so that we can force the binding expression to update the source of the binding with the new property value. This would look like this

_bindingExpression = element.GetBindingExpression(BoundProperty);

And to update the source (i.e in the property changed handler of the attached property) we would do this

_bindingExpression.UpdateSource();

How is this approach generic?

Well let’s see what we did in the “Dig Deeper” section.

- We are getting a dependency property by name

- We get the Binding Expression from that dependency property

- We create an attached property which will be our way of hooking to property changes of a specific dependency property.

mmm… So as such we can have 1 attached property of type string that will generate this hook and update the source for us. If we do this we would have something like this in our XAML

<TextBox Text=”{Binding SomeText, Mode=TwoWay}” local:UpdateSourceTrigger.PropertyName=”Text” />

Not great but not too bad, it will do the trick for now… So here is the code for the attached property (you have to download the sample project)… Its exactly what I explained in the section above.

Please note that I am creating the hook inside a separate class UpdateSourceTriggerProxy. I am doing that so that the operation is atomic and everytime you use this approach we have a different instance of UpdateSourceTriggerProxy doing the hook for updates and the actual update. The object instance we be kept alive because of the property changed delegate.

Download sample project here.

UpdateSourceTrigger PropertyChanged for Silverlight 4 Binding ?

Problem Definition

In Silverlight 4 there is no way out of the box to specify that a certain binding should update the source on PropertyChanged, the options for the UpdateSourceTrigger are LostFocus and Explicit.

These options are more or less what you really need for most scenarios, yet sometimes you want to have the ability to update the binding while a property is changing. A use case would be, you have a textbox and you want to apply some validations while the user is typing, maybe you enable a button if the text entered is correct or disable it if it is not correct.

Many times developers end up writing code behind in order to achieve this. Problem with this is that if you need it in multiple places you end up copying and pasting code for code behind. In this article I will show how one can workaround this problem by resorting to the mighty Attached Properties.

Using an Attached Property to workaround this problem

By using an attached property we can have the code to update the source on property changed. For this demo I will focus on how to make this work for a TextBox in Silverlight. In future posts I will show how you can have a generic way of dealing with this issue.

The attached property will give us the instance of the object the attached property is being applied to, with the reference of the object (in our case the TextBox) at hand we can hook to the TextChanged and update the binding. In order to update the binding you can use the GetBindingExpression method of the UI element. Then we can simple call the UpdateSource on the BindingExpression and viola the trick is done…

The Attached Property would look like this

using System.Windows;

using System.Windows.Controls;

 

namespace SilverlightUpdateSourceTrigger

{

    public class UpdateSourceTrigger

    {

        #region TextChangeUpdateSourceTrigger

 

        /// <summary>

        /// TextChangeUpdateSourceTrigger Attached Dependency Property

        /// </summary>

        public static readonly DependencyProperty TextChangeUpdateSourceTriggerProperty =

            DependencyProperty.RegisterAttached("TextChangeUpdateSourceTrigger", typeof(bool), typeof(UpdateSourceTrigger),

                new PropertyMetadata((bool)false,

                    new PropertyChangedCallback(OnTextChangeUpdateSourceTriggerChanged)));

 

        /// <summary>

        /// Gets the TextChangeUpdateSourceTrigger property. This dependency property 

        /// indicates ....

        /// </summary>

        public static bool GetTextChangeUpdateSourceTrigger(DependencyObject d)

        {

            return (bool)d.GetValue(TextChangeUpdateSourceTriggerProperty);

        }

 

        /// <summary>

        /// Sets the TextChangeUpdateSourceTrigger property. This dependency property 

        /// indicates ....

        /// </summary>

        public static void SetTextChangeUpdateSourceTrigger(DependencyObject d, bool value)

        {

            d.SetValue(TextChangeUpdateSourceTriggerProperty, value);

        }

 

        /// <summary>

        /// Handles changes to the TextChangeUpdateSourceTrigger property.

        /// </summary>

        private static void OnTextChangeUpdateSourceTriggerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)

        {

            TextBox textBox = d as TextBox;

            if (textBox == null)

                return;

 

            bool newTextChangeUpdateSourceTrigger = (bool)d.GetValue(TextChangeUpdateSourceTriggerProperty);

 

            if (newTextChangeUpdateSourceTrigger)

                textBox.TextChanged += OnTextChanged;

            else

                textBox.TextChanged -= OnTextChanged;

        }

 

        static void OnTextChanged(object sender, TextChangedEventArgs e)

        {

            TextBox textBox = sender as TextBox;

            var binding = textBox.GetBindingExpression(TextBox.TextProperty);

            binding.UpdateSource();

        }

        #endregion

        

    }

}

Enjoy and Happy XMAS Smile

Strong naming an assembly without having the actual source code

Today I had a blocking issue, I was in the process of Strong naming my assemblies yet I was referencing a third party assembly that was not strongly named. This cause a compilation error :S what to do????

A colleague David Field sent me 2 command line snippets that do just the thing…

Basically the idea is to use ILDASM.exe (which comes with .net SDK) to convert the dll to il and then use ILASM to make that IL badk into a dll and sign it. (please note you need an SNK file, you can create one easily with the sn.exe or just use one from the other assemblies you are signing)

the magic of ILDASM and ILASM >>

ildasm myassembly.dll /out:myassembly.il

where myassembly is the name of the DLL

and then we convert that IL back in a dll and sign it with ILASM

ilasm myassembly.il /dll /key=MyStringNameFile.snk

Hope you find this useful I sure did

Infusion Malta is looking for talents

 

logo

 

I’ve been working for Infusion for over a year now and I must say, even though I complain a lot (yea I am one of those guys that complains and complains and complains), its truly an amazing place to work! You get to work on cool cutting edge technology projects and to top it off you get to work with awesome people (probably bigger Geeks than you!).

I love the fact that Infusion is open to new ideas, case in point “Infusion Malta”; I was talking to Managing Director of Infusion London and told him “what if we open an Infusion Malta?”, and here we are today :)
*P.S Malta is where I was born… more info on Malta can be found be goggling it :P

So back to the original subject :P We are looking into building a small but efficient team in Malta, I call it Infusion SWAT team :) We are looking for both developers and designers…

For Developers >>
1. You must be a Geek
2. Good C# skills
3. open to work on new technologies like Win Mob7 and Surface
3. Want to learn/work on WPF and Silverlight.
4. Willing to work with me :P

For Designers >>
1. Good in Visual and Interactive design.
2. Want to learn/work on Expression Blend
3. Willing to work with those other strange people… yea I think they call them developers..

Hope I got you all excited and that you’ll send your CV to me at mgrech@infusion.com :)

see you in Malta :)

Adding more goodies in MEFedMVVM

Thanks to some good feedback from the community and also some really awesome help from Glenn Block and Sasha Barber, I added some new stuff to MEFedMVVM.

The core 3 additions are

- Reloading of design time data in Blend as you compile in Visual Studio (Patch by Chris Szabo)

      Before this patch you had to close and re open Blend everytime you did a change in your ViewModel for Blend to pick up this change. Chris Szabo sent me a code snippet showing me how I could overcome this issue. Very cool Chris!!!!!

- Added a new method in IComposer so that you can specify a list of custom ExportProviders.

      A user of Cinch suggested this feature since he had some ExportProvider he wanted to use in MEFedMVVM for versioning of objects. Now the IComposer has a new method that looks like this

image

You can return a list of ExportProviders or if you do not want to just return null. MEFedMVVM will attach its own ExportProvider even if you return null. (MEFedMVVM uses the ExportProvider for IContextAware services such as IVisualStateManager so that it can inject the View that requested the ViewModel)

-

- Added 2 new attached properties to make things more clear.

By default Exports in MEF are treated as Shared. This implies that if before you did an [ExportViewModel(“MyVM”] without specifying a [PartCreationPolicy(CreationPolicy.NonShared)] the ViewModel would be exported as a shared item so all imports get the same instance of the ViewModel. Also this implies that the ViewModel would never be garbage collected since MEF will keep its instance alive. The workaround for this would be to specify [PartCreationPolicy(CreationPolicy.NonShared)] where you put the ExportViewModel attribute. Once you know this its all good but if you are new to MEF maybe it is not that obvious that exports are by default Shared. So in order to make this crystal clear I added 2 new attached properties SharedViewModel and NonSharedViewModel, which will impose the CreationPolicy on the ViewModel you want to export (this is like doing the CreationPolicy on the Import if you were doing standard MEF). Glenn Block came up with this idea, kudos to Glenn!!!!

 

Besides these changes I also did some bug fixing here and there and some minor changes as per request …

- Export for ViewModel had an incorrect ImportCardinality. now the ImportCardinality is set to ExactlyOne.
- DataContextAware ViewModels used to call the DesignTimeInitialization 2 times, this is now fixed.
- Exposed the MEFedMVVM CompositionContainer, you can now access the CompositionContainer directly by doing this ViewModelRepoitory.Instance.Resolver.Container. This is useful if you want to get some Exported object from the CompositionContainer that MEFedMVVM is using.
- Fixed issue with ImportMany. This was a problem in the ExportProvider of MEFedMVVM.
- Added propertyObserver. you can see more about this here
- Fixed issue with DelegateCommand (was not hocking automatically to the CanExecute of the Command Manager in WPF)

Hope you enjoy MEFedMVVM and as always keep feedback coming !

Closures in C# can be evil

I had a problem with yield and closures. A friend Glenn Block gave me a good link on this. you can read it here >> http://codebetter.com/blogs/matthew.podwysocki/archive/2008/09/12/side-effects-and-functional-programming.aspx

here is an abstract from the blog about the problem. This can cause a lot of pain and that is why I am sharing it so that you do not fall in the same trap!

Closures and Lazy Evaluation

One last topic for this post revolves around variable instantiation around closures and what it means to you in regards to lazy evaluation.  Let’s look at a quick example of some of the issues you might face. 

C#

var contents = new List<Func<int>>();
var s = new StringBuilder();
for (var i = 4; i < 7; i++)
    contents.Add(() => i);
for (var k = 0; k < contents.Count; k++)
    s.Append(contents[k]());
Console.WriteLine(s);

What we might expect the results to be in this case would be 456.  But that’s not the case at all here.  In fact, the answer you will get is 777.  Why is that?  Well, it has to do with the way that the C# compiler creates a helper class to enable this closure.  If you’re like me and have Resharper, you’ll notice that it gives a warning about this with "Access to modified closure".  If we change this to give ourselves a local variable inside the loop closure construct to initialize the value properly.  If we do that and change our code, it will now look like this:

C#

var contents = new List<Func<int>>();
var s = new StringBuilder();
for (var i = 4; i < 7; i++)
{
var j = i;
    contents.Add(() => j);
}
for (var k = 0; k < contents.Count; k++)
    s.Append(contents[k]());
Console.WriteLine(s);

Jason Olson has a pretty good explanation in his post "Lambdas – Know Your Closures".

 

Hope it helps!

INotifyPropertyChanged… I am fed up of handling events just to know when a property changed

The INotifyPropertyChanged is what tells the WPF/SL binding that a property changed and that the binding should be updated. For this purpose its quite good. But what many times we end up doing is; handling the PropertyChanged in code so that we get notified that a property changed. An example is a ViewModel that need to know when a property in the underlying model changed and if it did it will do something to facilitate the View.

Doing this in code is a bit ugly because you base everything on “magic strings”.. something like this

image

Another problem is that if you use an anonymous delegate you need to do loads of tricks in order to unregister to the event.

In order to over come this I created a PropertyObserver that handles these 2 issues. (Please note that there are already others, Philip Sumi has a good one here and  Josh Smith has a good one here. I created my own since I wanted to have extra + different way of doing it). Also this problem can be solved easily using Rx, I am doing this sample so that you do not need to depend on Rx.

The implementation I did is very simple, I created a PropertyObserver class that uses lambdas so that you tell it what property you want to subscribe to and pass an action to do your “Property Changed handling”. What I also did is an attached method so that all objects that implement INotifyPropertyChanged can simple handle the property changed… so the code looks like this

image

One would ask and how do I unregister? is this using weak event pattern? The answer is NO. I wanted to keep it simple and cross platform (for WPF and SL). what you can do is a more Rx approach… basically in RX if you subscibe to something you get an IDisposable in return so that you can Dispose (i.e in our case unsubscribe) when you want like this

image

as you can see here I am wrapping the call in a using statement… but if you need to unsubscribe in any specific state you can store the IDisposable that you get from the Do call and call Dispose to unsubscribe.

Many times you need this for only one time i.e a property changes you do something and you do not want to get called any more times. For this I created a DoOnce. This will unsubscribe for you once the property changes once. The API is very similar and looks like this

image

That’s more or less it.

Big thanks go to Diego Colombo and John Rayner (two champs that work with me) for the help and input they gave me on this :) You rock guys!

You can download the code here.

OR if you have MEFedMVVM download the latest version since its in MEFedMVVM.