Xml namespace simplified in Silverlight 4.0

 

A feature added to Silverlight 4 that has not received much attention is the introduced support for the XmlnsDefinition and XmlnsPrefix attributes in custom assemblies. These attributes has been supported in WPF since day one, and has finally made their way into Silverlight as well.

The XmlnsDefinitionAttribute is used for mapping one or more CLR namespaces to one or more XML namespaces. The benefit of doing so is that
1) The user does not have to think or know about the CLR namespaces or assembly names when adding xmlns imports in XAML files
2) Because you can map several CLR namepaces to a single XML namespace, you can get away with a single XML namespace in your XAML files instead of one pr. CLR namespace when referencing components in your custom assemblies.

You typically define the XmlnsDefinitionAttribute in the AssemblyInfo.cs-file like so:

[assembly: XmlnsDefinition("http://schemas.mycompany.com/silverlight","MyCompany.Windows.Controls")]
[assembly: XmlnsDefinition("http://schemas.mycompany.com/silverlight", "MyCompany.Windows.Behaviors")]

Then, in a XAML file, you can simply add an xmlns import like this;

<UserControl x:Class="SilverlightApplication2.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:myCompany="http://schemas.mycompany.com/silverlight"

and now you can access the types specified in MyCompany.Windows.Controls and MyCompany.Windows.Behaviors throught the myCompany xmlns prefix.

Further, you can use XmlnsPrefixAttribute to specify a default prefix associated with a XML namespace. This prefix is used by the Visual Studio and Blend designer when you drag/drop custom components from the toolbox onto the designer surface.

[assembly: XmlnsPrefix("http://schemas.mycompany.com/silverlight","myCompany")]
[assembly: XmlnsDefinition("http://schemas.mycompany.com/silverlight","MyCompany.Windows.Controls")]
[assembly: XmlnsDefinition("http://schemas.mycompany.com/silverlight", "MyCompany.Windows.Behaviors")]


 

 

Object-To-Object Binding / ViewModel-To-ViewModel Binding

 

There may be times when you need to pass data back and forth between ViewModels in a loosly coupled way, without having to handle this in your ViewModels or code behind. Consider a parent-child ViewModel scenario, where your parent ViewModel may contain data resulting in the creation of multiple child ViewModels, for example the case when your parent ViewModel has a collection of business objects, and you need to enable editing each business object separately unsing their own View-ViewModels.

The XAML code below has an ItemsControl which binds to the Items collection of the ViewModel set as the DataContext of the parent View.
This will create an instance of the ChildView for each member of the Items collection.

<
ItemsControlItemsSource="{BindingPath=Items}"HorizontalAlignment="Center"VerticalAlignment="Center">
            <
ItemsControl.ItemTemplate>
                <
DataTemplate>
                   
<local:ChildView>
                  
</local:ChildView>
                </DataTemplate>
            </
ItemsControl.ItemTemplate>
        </
ItemsControl>

What we would like, is to pass each item in the Items collection to the ViewModel of each created ChildView so that an action can be taken based on that information.
In order to do this, we can create a binding which binds to a property of the ChildView ViewModel, and one binding that binds to the item from the parent ViewModel Items collection. Then, we need to tie those tow bindings together so that when one of the bound items changes, the other one gets updated as well.

A solution to this may look like this;

<ItemsControl ItemsSource="{Binding Path=Items}" HorizontalAlignment="Center" VerticalAlignment="Center">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <TextBlock Text="{Binding}" Visibility="Collapsed" x:Name="HiddenTextBlock"/>
                        <local:ChildView>
                            <local:BindingBehaviors.ObjectToObjectBinding>
                                <local:ObjectToObjectBinding Source="{Binding Path=Text, ElementName=HiddenTextBlock}" Target="{Binding Path=MyProperty, Mode=TwoWay}"/>
                            </local:BindingBehaviors.ObjectToObjectBinding>
                        </local:ChildView>
                    </Grid>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

What we have done here is to create a binding behavior that ties a Source and Target binding together so that when the Source changes, the Target (MyProperty) gets updated as well. For this example to work, we needed to do a little “hack” by defining the Source binding to bind to a TextBlock which holds on to a member of the Items collection from the parent ViewModel (as the Items collection in this case happens to contain strings. If you need to store an Object, change the TextBlock to a ContentPresenter, for example, and bind to the Content property instead). The Target binding defines a binding to the MyProperty property of the ChildView ViewModel, so that MyProperty will get the value of the item from the Items collection when the ChildView is loaded.

Besides the BindingBehavior class that defines the ObjectToObjectBinding attached property, we need a class for our Source and Target bindings, and also a class that handles / relays the data updates between the Source and Target.

To hold on to our Source and Target bindings, we need a simple ObjectToObjectBinding class with only two properties;

public class ObjectToObjectBinding
    {
        public Binding Source { get; set; }
        public Binding Target { get; set; }
    }

The class that handles exchanging data between the Source and Target is also as simple as it gets; All it does is copy the value of the Source property to the value of the Target propery, and vica verca, when a change occurs.

public class DataRelay : DependencyObject
    {
        #region Source

        public static readonly DependencyProperty SourceProperty =
            DependencyProperty.Register("Source", typeof(object), typeof(DataRelay),
                new PropertyMetadata(null, new PropertyChangedCallback(OnSourceChanged)));

        public object Source
        {
            get { return (object)GetValue(SourceProperty); }
            set { SetValue(SourceProperty, value); }
        }

        private static void OnSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((DataRelay)d).OnSourceChanged(e);
        }

        protected virtual void OnSourceChanged(DependencyPropertyChangedEventArgs e)
        {
            this.Target = e.NewValue;
        }

        #endregion

        #region Target

        public static readonly DependencyProperty TargetProperty =
            DependencyProperty.Register("Target", typeof(object), typeof(DataRelay),
                new PropertyMetadata(null, new PropertyChangedCallback(OnTargetChanged)));

        public object Target
        {
            get { return (object)GetValue(TargetProperty); }
            set { SetValue(TargetProperty, value); }
        }

        private static void OnTargetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((DataRelay)d).OnTargetChanged(e);
        }

        protected virtual void OnTargetChanged(DependencyPropertyChangedEventArgs e)
        {
            this.Source = e.NewValue;
        }

        #endregion
    }


The code needed to tie the two bindings together is pretty simple;

private static void OnObjectToObjectBindingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ObjectToObjectBinding binding = e.NewValue as ObjectToObjectBinding;
            if (binding != null)
            {
                if (binding.Source == null)
                    throw new ArgumentNullException("binding.Source");
                if (binding.Target == null)
                    throw new ArgumentNullException("binding.Target");

                DataRelay dataRelay = new DataRelay();

                BindingBehaviors.SetObjectToObjectBindingRelay(d, dataRelay);

                BindingOperations.SetBinding(dataRelay, DataRelay.SourceProperty, binding.Source);
                BindingOperations.SetBinding(dataRelay, DataRelay.TargetProperty, binding.Target);
            }
        }

What we have done here, is created a private attached property called ‘ObjectToObjectBindingRelay’ which allows us to attach an instance of the DataRelay object to a DependencyObject (in this case, our ChildView).

Next, we sets the Source binding to update DataRelay Source property, and the Target binding to update the Target property, so that data is exchanged between the source and target object when data changes.

Download source code

Using Bindings in Styles in Silverlight

 

One of the differences between WPF and Silverlight is that using Bindings when setting properties in styles is still not supported (SL 4). If you try to do so, your application will simply crash.
In WPF, you can do something like this;

<Style TargetType="{x:Type ListBoxItem}">
       <Setter Property="Background" Value="{Binding Path=MyColor}"/>
</Style>

Although not directly supported, you can achieve the same thing in Silverlight using attached properties. The workaround is to specify an Attached Property in the Setter Property, and then use a “proxy” in the Setter Value to set up the binding between the actual property of the UI element and the object from the data binding. This technique can also be used for things like wiring up command to react to user input, for example when a user double clicks a ListBoxItem.



The following example shows how to set the background color of a ListBoxItem through data binding, and also how to react to a double click on the item.

<ListBox x:Name="listBox1">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Path=Name}"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
            <ListBox.ItemContainerStyle>
                <Style TargetType="ListBoxItem">
                    <Setter Property="b:BindingBehavior.PropertyBinding">
                        <Setter.Value>
                            <b:PropertyBinding Binding="{Binding Path=BackgroundBrush}" Property="Background"/>
                        </Setter.Value>
                    </Setter>
                    <Setter Property="b:BindingBehavior.DoubleClickCommandBinding">
                        <Setter.Value>
                            <b:CommandBinding Command="{Binding Path=DataContext.TestCommand, ElementName=LayoutRoot}"
                                              CommandParameter="{Binding}"/>
                        </Setter.Value>
                    </Setter>
                </Style>
            </ListBox.ItemContainerStyle>
        </ListBox>

As you can see, both the Setter Properties have Attached Properties defined instead of the actual property names of the ListBoxItem. In the Setter Values, I have added my proxy classes where I have specified the bindings and the name of the ListBoxItem property I want a binding to apply to.

The BindingProperty proxy class is very simple and contains only two properties; one for holding the name of the property you want to bind to and one for the binding itself.

public class PropertyBinding
    {
        public Binding Binding { get; set; }
        public string Property { get; set; }
    }

The BindingBehavior class is responsible for creating the actual binding based on an instance of the PropertyBinding. It does so using reflection on the ListBoxItem to locate the dependency property specified in the Property attribute of the PropertyBinding proxy instance.

private static void OnPropertyBindingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            FrameworkElement frameworkElement = d as FrameworkElement;
            if (frameworkElement == null)
            {
                throw new ArgumentException("The PropertyBinding behavior can only be applied to FrameworkElement types");
            }

            PropertyBinding styleBinding = e.NewValue as PropertyBinding;
            if (styleBinding != null)
            {
                string depPropName = string.Concat(styleBinding.Property, "Property");
                if (depPropName.IndexOf('.') > -1)
                {
                    int index = depPropName.LastIndexOf('.');
                    depPropName = depPropName.Substring(index);
                }
                FieldInfo dependencyPropertyField = frameworkElement.GetType().GetField(depPropName, BindingFlags.Public
                    | BindingFlags.Static
                    | BindingFlags.FlattenHierarchy);
                if (dependencyPropertyField != null)
                {
                    DependencyProperty dependencyProperty = dependencyPropertyField.GetValue(null) as DependencyProperty;
                    if (dependencyProperty != null)
                    {
                        frameworkElement.SetBinding(dependencyProperty, styleBinding.Binding);
                    }
                }
            }

        }
For the command binding, a similar approach is used. The CommandBinding proxy class contains a Binding property for setting the Command and CommandParameter, and then the BindingBehavior class creates the actual binding in the OnXXXChanged event handler.

public class CommandBinding
    {
        public Binding Command { get; set; }
        public Binding CommandParameter { get; set; }
    }
private static void OnDoubleClickCommandBindingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            FrameworkElement element = d as FrameworkElement;
            if (element == null)
            {
                throw new InvalidOperationException("This behavior can only be applied to FrameworkElement types");
            }

            CommandBinding styleBinding = e.NewValue as CommandBinding;
            if (styleBinding != null)
            {
                element.SetBinding(BindingBehavior.DoubleClickProperty, styleBinding.Command);
                if (styleBinding.CommandParameter != null)
                {
                    element.SetBinding(BindingBehavior.DoubleClickParameterProperty, styleBinding.CommandParameter);
                }
                else
                {
                    element.ClearValue(BindingBehavior.DoubleClickParameterProperty);
                }
            }
            else
            {
                element.ClearValue(BindingBehavior.DoubleClickProperty);
                element.ClearValue(BindingBehavior.DoubleClickParameterProperty);
            }
        }

 

The source code can be downloaded from here. (VS 2010 Solution)