<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Dude, where is my Kaizen? &#187; WPF</title>
	<atom:link href="http://www.bjoernrochel.de/tag/wpf/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.bjoernrochel.de</link>
	<description>Björn Rochel&#039;s weblog</description>
	<lastBuildDate>Mon, 21 Jun 2010 07:26:00 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Notifications the WPF way (I guess), Part III</title>
		<link>http://www.bjoernrochel.de/2009/11/02/notifications-the-wpf-way-i-guess-part-iii/</link>
		<comments>http://www.bjoernrochel.de/2009/11/02/notifications-the-wpf-way-i-guess-part-iii/#comments</comments>
		<pubDate>Mon, 02 Nov 2009 17:59:00 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/?p=584</guid>
		<description><![CDATA[Today I would like to conclude my little series about the Notification Pattern with (I guess at least for some of you) the most interesting part: Today is all about displaying Notifications in the UI. This post will guide you through all the steps I took in order to achieve the affect I demonstrated in [...]]]></description>
			<content:encoded><![CDATA[<p>Today I would like to conclude my little series about the Notification Pattern with (I guess at least for some of you) the most interesting part: <strong>Today is all about displaying Notifications in the UI</strong>. This post will guide you through all the steps I took in order to achieve the affect I demonstrated in the <a href="http://www.bjoernrochel.de/2009/10/20/notifications-the-wpf-way-i-guess-part-i/" target="_blank">introduction post</a>.</p>
<p>Last time I showed how I&#8217;m transfering Notifications from the ViewModel into the logical WPF tree. If you&#8217;ve not read the previous posts, please give them some minutes, because I&#8217;m not going to repeat a lot of them today. You can find them <a href="http://www.bjoernrochel.de/2009/08/28/implementing-the-notification-pattern-using-dataannotation-validators/">here</a>, <a href="http://www.bjoernrochel.de/2009/10/20/notifications-the-wpf-way-i-guess-part-i/">here</a> and <a href="http://www.bjoernrochel.de/2009/10/27/notifications-the-wpf-way-i-guess-part-ii/">here</a>.</p>
<p>As always, a quick reminder: <em>What I&#8217;m showing is in this series is <strong>how I&#8217;ve implemented the Notification Pattern</strong>. I&#8217;m not claiming that it&#8217;s the only or the best way to do so. However, it&#8217;s the one that works very good for me.<br />
</em></p>
<p><strong><font size="4">How to get the red border effect</font></strong></p>
<p>The red border has to be displayed when Notifications exists for a control. Technically this means<br />
that the attached property &#8220;Notifications&#8221; (which is defined on the ValidationBehavior class I showed in the last post) is set to a non empty NotificationCollection.</p>
<p>We can react to this by defining a DataTrigger for this. In my own words I would describe DataTriggers as</p>
<p><em>An in XAML defined event handler with a related criteria. When the criteria is matched the DataTrigger gets executed. When it isn&#8217;t matched any more, the DataTrigger reverts the state of the element on which it&#8217;s defined to the state before it was executed.</em></p>
<p>Sounds usable for our purpose. Think about it, we only want to show the red border, when the attached property is set to a non empty collection. If the property is reset the border needs to disappear.</p>
<p>The only difficulty with DataTriggers we need to solve on our way is how to configure that exactly in XAML. DataTriggers can be easily set on primitives (such as string, bool, etc.) or null, but there isn&#8217;t an out of the box way for setting our criteria in XAML.</p>
<p>However you can use a custom Converter for converting our value to a primitive &#8220;switch&#8221;.</p>
<pre class="brush: csharp">

    [ValueConversion(typeof(NotificationCollection), typeof(bool))]
    public class ContainsNotificationConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return (value != null &amp;amp;&amp;amp; value is NotificationCollection &amp;amp;&amp;amp; ((NotificationCollection)value).Any());
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    }
</pre>
<p>Using this converter we can define our DataTrigger in the Style for Controls like this:</p>
<pre class="brush: xml">

   &lt;Fx:ContainsNotificationConverter x:Key=&quot;notificationConverter&quot; /&gt;

   &lt;Style TargetType=&quot;Control&quot;&gt;
        &lt;Setter Property=&quot;Fx:ValidationBehavior.IsEnabled&quot; Value=&quot;true&quot; /&gt;
        &lt;Style.Triggers&gt;
            &lt;DataTrigger
                Binding=&quot;{Binding Path=(Fx:ValidationBehavior.Notifications),
                Converter={StaticResource notificationConverter},
                RelativeSource={x:Static RelativeSource.Self}}&quot; Value=&quot;true&quot;&gt;
                &lt;Setter Property=&quot;BorderBrush&quot; Value=&quot;Red&quot; /&gt;
                &lt;Setter Property=&quot;BorderThickness&quot; Value=&quot;2&quot; /&gt;
            &lt;/DataTrigger&gt;
        &lt;/Style.Triggers&gt;
    &lt;/Style&gt;
</pre>
<p><b><font size="4">How to display Notifications in a Tooltip</font></b></p>
<p>Solving the Tooltip requirement was a bit more tricky (at least for me). It took me quite some time to figure out how to do this in WPF. The solution I&#8217;m going to show uses only XAML based code. </p>
<p><b>1. Integrating the Tooltip into the DataTrigger</b></p>
<p>We simply use our DataTrigger to automatically set theTooltip of a Control in case Notifications exist. </p>
<pre class="brush: xml">

   &lt;ToolTip x:Key=&quot;ValidationErrorTooltip&quot; /&gt;

   &lt;Style TargetType=&quot;Control&quot;&gt;
        &lt;Setter Property=&quot;Fx:ValidationBehavior.IsEnabled&quot; Value=&quot;true&quot; /&gt;
        &lt;Style.Triggers&gt;
            &lt;DataTrigger
                Binding=&quot;{Binding Path=(Fx:ValidationBehavior.Notifications),
                Converter={StaticResource notificationConverter},
                RelativeSource={x:Static RelativeSource.Self}}&quot; Value=&quot;true&quot;&gt;
                &lt;Setter Property=&quot;BorderBrush&quot; Value=&quot;Red&quot; /&gt;
                &lt;Setter Property=&quot;BorderThickness&quot; Value=&quot;2&quot; /&gt;
                &lt;Setter Property=&quot;ToolTip&quot; Value=&quot;{StaticResource ValidationErrorTooltip}&quot; /&gt;
            &lt;/DataTrigger&gt;
        &lt;/Style.Triggers&gt;
    &lt;/Style&gt;
</pre>
<p>Now the UI looks really crappy. The tooltip is not recognizable as one.</p>
<p><img src="http://www.bjoernrochel.de/wp-content/uploads/2009/11/signup_emptytooltip1.jpg" alt="Horrible Tooltip" class="size-full wp-image-596" /></p>
<p><b>2. Using a ControlTemplate to style the Tooltip</b></p>
<p>In order to shape the appearance of the Tooltip we can use Styles again. You can change the whole visual appearance of a Control using Styles and ControlTemplates. The template I defined consists mostly of a DockPanel containing a Label (which provides the tooltips caption) and a TextBlock (which will later contain the Notification messages).</p>
<pre class="brush: xml">

    &lt;Style x:Key=&quot;ErrorTooltipSyle&quot; TargetType=&quot;ToolTip&quot;&gt;
        &lt;Setter Property=&quot;Template&quot;&gt;
            &lt;Setter.Value&gt;
                &lt;ControlTemplate TargetType=&quot;ToolTip&quot;&gt;
                    &lt;Border BorderBrush=&quot;Black&quot; BorderThickness=&quot;1&quot;&gt;
                        &lt;DockPanel&gt;
                            &lt;Label DockPanel.Dock=&quot;Top&quot;
                            	FontWeight=&quot;Bold&quot;
                            	Background=&quot;Red&quot;
                            	Foreground=&quot;White&quot;
                            	Content=&quot;Validation Error&quot; /&gt;
                            &lt;TextBlock
                            	Padding=&quot;10&quot;
                            	Background=&quot;White&quot;
                            	Foreground=&quot;Black&quot;
                            	TextWrapping=&quot;WrapWithOverflow&quot; /&gt;
                        &lt;/DockPanel&gt;
                    &lt;/Border&gt;
                &lt;/ControlTemplate&gt;
            &lt;/Setter.Value&gt;
        &lt;/Setter&gt;
    &lt;/Style&gt;

    &lt;!-- Notice the defined Style --&gt;
    &lt;ToolTip x:Key=&quot;ValidationErrorTooltip&quot; Style=&quot;{StaticResource ErrorTooltipSyle}&quot; /&gt;

    &lt;Style TargetType=&quot;Control&quot;&gt;
        &lt;Setter Property=&quot;Fx:ValidationBehavior.IsEnabled&quot; Value=&quot;true&quot; /&gt;
        &lt;Style.Triggers&gt;
            &lt;DataTrigger
                Binding=&quot;{Binding Path=(Fx:ValidationBehavior.Notifications),
                Converter={StaticResource notificationConverter},
                RelativeSource={x:Static RelativeSource.Self}}&quot; Value=&quot;true&quot;&gt;
                &lt;Setter Property=&quot;BorderBrush&quot; Value=&quot;Red&quot; /&gt;
                &lt;Setter Property=&quot;BorderThickness&quot; Value=&quot;2&quot; /&gt;
                &lt;Setter Property=&quot;ToolTip&quot; Value=&quot;{StaticResource ValidationErrorTooltip}&quot; /&gt;
            &lt;/DataTrigger&gt;
        &lt;/Style.Triggers&gt;
    &lt;/Style&gt;
</pre>
<p>Our UI now looks like this. </p>
<p><img src="http://www.bjoernrochel.de/wp-content/uploads/2009/11/signup_tooltipwithcontroltemplate1.jpg" alt="Tooltip with ItemSource" width="411" height="198" class="size-full wp-image-597" /></p>
<p>Not as crappy as before but we&#8217;re not finished yet, because we&#8217;re not displaying Notifications yet.</p>
<p><b>3. Define Databinding on the Tooltip</b></p>
<p>Defining the Databinding was probably the hardest step I had to take. The problem is that you need to get the NotificationCollection from the Control the ToolTip is displayed on. Being not a WPF pro figuring out how to do this took quite some time. Anyway, in order to get the Notification there isn&#8217;t much you need to do.</p>
<p>The trick is to bind against the property PlacementTarget on the ToolTip class itself. This property holds the reference to the Control on which the Tooltip is displayed. All we need to do is to add a Binding to the Style definition that sets the DataContext of the ToolTip to the related control.</p>
<pre class="brush: xml">

    &lt;Style x:Key=&quot;ErrorTooltipSyle&quot; TargetType=&quot;ToolTip&quot;&gt;
        ...
        &lt;Setter Property=&quot;DataContext&quot; Value=&quot;{Binding Path=PlacementTarget, RelativeSource={x:Static RelativeSource.Self}}&quot; /&gt;
        ...
    &lt;/Style&gt;
</pre>
<p>The next step we need to take is setting up the Binding for our attached property &#8220;Notifications&#8221;. Because a NotificationCollection can contain more than one Notification I used the ItemsControl for displaying them in the content area of the ToolTip.</p>
<pre class="brush: xml">

    &lt;Style x:Key=&quot;ErrorTooltipSyle&quot; TargetType=&quot;ToolTip&quot;&gt;
      &lt;Setter Property=&quot;DataContext&quot; Value=&quot;{Binding Path=PlacementTarget, RelativeSource={x:Static RelativeSource.Self}}&quot; /&gt;
        &lt;Setter Property=&quot;Template&quot;&gt;
            &lt;Setter.Value&gt;
                &lt;ControlTemplate TargetType=&quot;ToolTip&quot;&gt;
                    &lt;Border BorderBrush=&quot;Black&quot; BorderThickness=&quot;1&quot;&gt;
                        &lt;DockPanel&gt;
                            &lt;Label DockPanel.Dock=&quot;Top&quot;
                            	FontWeight=&quot;Bold&quot;
                            	Background=&quot;Red&quot;
                            	Foreground=&quot;White&quot;
                            	Content=&quot;Validation Error&quot; /&gt;
                            &lt;TextBlock
                            	Padding=&quot;10&quot;
                            	Background=&quot;White&quot;
                            	Foreground=&quot;Black&quot;
                            	TextWrapping=&quot;WrapWithOverflow&quot;&gt;

                                &lt;!-- This control displays our Notifications --&gt;
                                &lt;ItemsControl x:Name=&quot;notifications&quot;
                                    HorizontalAlignment=&quot;Stretch&quot;
                                    Margin=&quot;10&quot;
                                    VerticalAlignment=&quot;Center&quot;
                                    ItemsSource=&quot;{Binding Path=(Fx:ValidationBehavior.Notifications), Mode=OneWay}&quot;/&gt;

                             &lt;/TextBlock&gt;
                        &lt;/DockPanel&gt;
                    &lt;/Border&gt;
                &lt;/ControlTemplate&gt;
            &lt;/Setter.Value&gt;
        &lt;/Setter&gt;
    &lt;/Style&gt;
</pre>
<p>Voila, our Notifications are finally displayed in the UI.</p>
<p><img src="http://www.bjoernrochel.de/wp-content/uploads/2009/11/signup_tooltipwithcontroltemplate2.jpg" alt="Tooltip with ControlTemplate" width="500" height="227" class="size-full wp-image-598" /></p>
<p><b>4. Styling the Notifications</b></p>
<p>In my initial post I showed a hyphen in front of each Notification. This is fairly easy to add, too. All you have to do is to define a DataTemplate for the Notification class and set it as the ItemTemplate of the ItemsControl we&#8217;re using.  </p>
<pre class="brush: xml">

    &lt;!-- Very simple data template --&gt;
    &lt;DataTemplate x:Key=&quot;NotificationTemplate&quot;&gt;
        &lt;StackPanel Orientation=&quot;Horizontal&quot;&gt;
            &lt;TextBlock&gt;-&lt;/TextBlock&gt;
            &lt;TextBlock x:Name=&quot;notification&quot; Text=&quot;{Binding}&quot; /&gt;
        &lt;/StackPanel&gt;
    &lt;/DataTemplate&gt;

    &lt;Style x:Key=&quot;ErrorTooltipSyle&quot; TargetType=&quot;ToolTip&quot;&gt;
      &lt;Setter Property=&quot;DataContext&quot; Value=&quot;{Binding Path=PlacementTarget, RelativeSource={x:Static RelativeSource.Self}}&quot; /&gt;
        &lt;Setter Property=&quot;Template&quot;&gt;
            &lt;Setter.Value&gt;
                &lt;ControlTemplate TargetType=&quot;ToolTip&quot;&gt;
                    &lt;Border BorderBrush=&quot;Black&quot; BorderThickness=&quot;1&quot;&gt;
                        &lt;DockPanel&gt;
                            &lt;Label DockPanel.Dock=&quot;Top&quot;
                            	FontWeight=&quot;Bold&quot;
                            	Background=&quot;Red&quot;
                            	Foreground=&quot;White&quot;
                            	Content=&quot;Validation Error&quot; /&gt;
                            &lt;TextBlock
                            	Padding=&quot;10&quot;
                            	Background=&quot;White&quot;
                            	Foreground=&quot;Black&quot;
                            	TextWrapping=&quot;WrapWithOverflow&quot;&gt;
                      		&lt;ItemsControl x:Name=&quot;notifications&quot;
                                    HorizontalAlignment=&quot;Stretch&quot;
                                    Margin=&quot;10&quot;
                                    VerticalAlignment=&quot;Center&quot;
                                    ItemsSource=&quot;{Binding Path=(Fx:ValidationBehavior.Notifications), Mode=OneWay}&quot;

                                    &lt;!-- This uses configures our template for Notifications --&gt;
                                    ItemTemplate=&quot;{StaticResource NotificationTemplate}&quot; /&gt;

		                &lt;/TextBlock&gt;
                        &lt;/DockPanel&gt;
                    &lt;/Border&gt;
                &lt;/ControlTemplate&gt;
            &lt;/Setter.Value&gt;
        &lt;/Setter&gt;
    &lt;/Style&gt;
</pre>
<p>DataTemplates are also the weapon of choice if you want to display errors in a different fashion than warnings (for instance by displaying a different icon). This is where we arrived.</p>
<p><img src="http://www.bjoernrochel.de/wp-content/uploads/2009/11/signup_tooltipfinishedjpg.jpg" alt="Tooltip finished" width="493" height="218" class="size-full wp-image-599" /></p>
<p><b><font size="4">Closing thoughts</font></b></p>
<p>What I like about the current solution is that it demonstrates in a nice way how different the programming model of WPF actually is compared to WinForms. The only imperative code we have is the code that transfers Notifications from our ViewModel into the logical tree. That&#8217;s it. The rest, the complete visual appeal of the Notifications, is a separated concern. Those two things can be changed independently from each other, even by different roles in a development team (Designer/Developer). Besides that I like the way the composition based WPF model helps my application code to stay focused and clean with only minimum implementation constraints on the ViewModel itself (the INotificationSource interface). </p>
<p>There&#8217;re certainly things to improve both in XAML and in the glue code but I consider it a good start to build on.</p>
<p>In case you&#8217;re interested in the complete code, I&#8217;ve uploaded it to a corner of the xUnit.BDDExtensions trunk. You can find it <a href="http://xunitbddextensions.googlecode.com/svn/trunk/Experiments/WPF/Notifications/"> here </a>. Feel free to do whatever you want with the code . . . </p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2009/11/02/notifications-the-wpf-way-i-guess-part-iii/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Notifications the WPF way (I guess), Part II</title>
		<link>http://www.bjoernrochel.de/2009/10/27/notifications-the-wpf-way-i-guess-part-ii/</link>
		<comments>http://www.bjoernrochel.de/2009/10/27/notifications-the-wpf-way-i-guess-part-ii/#comments</comments>
		<pubDate>Tue, 27 Oct 2009 19:29:16 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/?p=574</guid>
		<description><![CDATA[Back again to my take on the Notification pattern with WPF. Last time I talked briefly about my motivation for this little series. This time we dive more into the nuts and bolts of my example implementation.
How the ViewModel notifies the UI
I defined an interface called INotificationSource for this. This interface defines only I member [...]]]></description>
			<content:encoded><![CDATA[<p>Back again to my take on the Notification pattern with WPF. Last time I talked briefly about my motivation for this little series. This time we dive more into the nuts and bolts of my example implementation.</p>
<p><b>How the ViewModel notifies the UI</b></p>
<p>I defined an interface called INotificationSource for this. This interface defines only I member which exposes a NotificationCollection. NotificationCollection is just a standard ObservableCollection&lt;Notification&gt; with some additional bits in it (such as retrieving a collection of Notifications for a given source). By deriving from ObservableCollection you get the CollectionChangedEvent on the collection for free.</p>
<pre class="brush: csharp">

public interface INotificationSource
{
    NotificationCollection Notifications {get;}
}
</pre>
<p>In my current app I&#8217;ve got a Layer Supertype for ViewModels which implements this interface.</p>
<p><b>Glue code for transferring Notifications from the ViewModel into the logical tree</b></p>
<p>As I mentioned in the last post I&#8217;m using the Attached Behavior Pattern for transferring Notifications from the ViewModel to the related elements in the logical tree (When I say related I&#8217;m referring to the FrameworkElements bound to my ViewModel via DataBinding). The class responsible for the transfer is a DependencyObject derived class, called ValidationBehavior. This class defines two attached DependencyProperties, IsEnabled and Notifications.</p>
<pre class="brush: csharp">

    public class ValidationBehavior : DependencyObject
    {
        public static readonly DependencyProperty IsEnabledProperty;
        public static readonly DependencyProperty NotificationsProperty;

        static ValidationBehavior()
        {
            IsEnabledProperty =  DependencyProperty.RegisterAttached(
                                    &quot;IsEnabled&quot;,
                                    typeof(bool),
                                    typeof(ValidationBehavior),
                                    new FrameworkPropertyMetadata(OnValidationBehaviorEnabled));

            NotificationsProperty = DependencyProperty.RegisterAttached(
                                    &quot;Notifications&quot;,
                                    typeof(NotificationCollection),
                                    typeof(ValidationBehavior),
                                    new PropertyMetadata(null));
        }

        public static bool GetIsEnabled(DependencyObject host)
        {
            return (bool) host.GetValue(IsEnabledProperty);
        }

        public static void SetIsEnabled(DependencyObject host, bool isEnabled)
        {
            host.SetValue(IsEnabledProperty, isEnabled);
        }

        public static NotificationCollection GetNotifications(DependencyObject host)
        {
            return (NotificationCollection)host.GetValue(NotificationsProperty);
        }

        public static void SetNotifications(DependencyObject host, NotificationCollection notification)
        {
            host.SetValue(NotificationsProperty, notification);
        }

   }
</pre>
<p>The attached DependencyProperty &#8220;IsEnabled&#8221; is used to attach our behavior to the target element marked with the property. Notice the OnValidationBehaviorEnabled handler which is called when the value of the registered attached DependencyProperty has changed.</p>
<p>The attached DependencyProperty &#8220;Notifications&#8221; will later hold the collection of Notifications extracted from the ViewModel by our attached behavior. By having the NotificationCollection as an attached property you&#8217;re able to bind against it from XAML (as we&#8217;ll see in the following post).</p>
<p>If you recall the last post about this topic, maybe you remember that I didn&#8217;t actually set the attached property IsEnabled in the ViewModels XAML file. You could configure the behavior in the related XAML file but I didn&#8217;t want to do this for all my ViewModels. Because of this I decided to use Styles for this. </p>
<pre class="brush: xml">

&lt;!-- The global application class --&gt;
&lt;Application x:Class=&quot;Notifications.App&quot;
    xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
    xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;&gt;
    &lt;Application.Resources&gt;
        &lt;ResourceDictionary Source=&quot;Resources/Theme.xaml&quot; /&gt;
    &lt;/Application.Resources&gt;
&lt;/Application&gt;

&lt;!-- My XAML file containing the resources --&gt;
&lt;ResourceDictionary
    xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
    xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
    xmlns:Fx=&quot;clr-namespace:Notifications.Fx&quot;&gt;

    &lt;Style TargetType=&quot;Control&quot;&gt;
        &lt;Setter Property=&quot;Fx:ValidationBehavior.IsEnabled&quot; Value=&quot;true&quot; /&gt;
    &lt;/Style&gt;

    &lt;Style TargetType=&quot;TextBox&quot; BasedOn=&quot;{StaticResource {x:Type Control}}&quot; /&gt;

&lt;/ResourceDictionary&gt;
</pre>
<p>When the Style is applied the IsEnabled attached property will be automatically set on all elements based on that style and this brings us into the position to hook into the elements events and access the elements data. The OnValidationBehaviorEnabled handler is actually straight forward.</p>
<pre class="brush: csharp">

        private static void OnValidationBehaviorEnabled(
            DependencyObject dependencyObject,
            DependencyPropertyChangedEventArgs args)
        {
            var frameworkElement = (FrameworkElement)dependencyObject;

            // Get the DataContext from the element. Mostly this DataContext is not directly
            // set on the element but rather derived from the parents DataContext
            var notificationSource = frameworkElement.DataContext as INotificationSource;

            if (notificationSource == null)
            {
                return;
            }

            // Clear related Notifications of an element when the element
            // got the focus.
            frameworkElement.GotFocus += ClearNotificationOnFocus;

            // Hook into the CollectionChanged event of the NotificationCollection.
            // I&#039;m using a closure here in order to capture the FrameworkElement.
            notificationSource.Notifications.CollectionChanged += (sender, collectionChangedArgs) =&gt;
            {
                var notifications = GetNotifications(notificationSource, frameworkElement);

                SetNotification(
                    frameworkElement,
                    notifications);
            };
        }
</pre>
<p>The anonymous event handler registered for the CollectionChangedEvent tries to get the collection of Notifications for the FrameworkElement. </p>
<pre class="brush: csharp">

        private static NotificationCollection GetNotifications(INotificationSource notificationSource, FrameworkElement frameworkElement)
        {
            return notificationSource.Notifications.AllNotificationsFor(frameworkElement.Name);
        }
</pre>
<p>As you can see this particular piece of code has a little quirk right now. It relies on the convention / assumption that the property on the ViewModel and the bound FrameworkElement share the same name. It was the easiest thing to do. It would also be easy to introduce another attached property for this in order to specify the name of the related ViewModel property. However this wouldn&#8217;t be 100% DRY because you&#8217;re most likely going to specify the property via the Binding MarkupExtension, too. I&#8217;m open to suggestions of how this correlation can be done better.</p>
<p>The last missing code piece is the handler which clears the Notification when it gets focus. It simply<br />
sets the attached Notification property to null.</p>
<pre class="brush: csharp">

        private static void ClearNotificationOnFocus(object sender, RoutedEventArgs e)
        {
            var elementWithNotification = (FrameworkElement)e.OriginalSource;
            elementWithNotification.SetValue(NotificationProperty, null);
        }
    }
</pre>
<p><b>Closing thoughts</b></p>
<p>I hope you&#8217;re getting a feeling for what I wanted to show with this little post series. Today I talked mostly about how Notifications can be transfered from the ViewModel into the WPF tree. While the code currently has some pieces in it that imho should be refactored (correlation of the Notifications, CollectionChangedEvent currently reloads all Notifications), I hope you saw in this post that it&#8217;s relatively easy to add such an ability to your app infrastructure without a) having a base class constraint b) a lot of imperative code and c) doing a lot of configuration.</p>
<p>The next post will conclude this little series mostly with XAML stuff. We&#8217;re going to cover how to combine the different tools (DataTrigger, DataTemplates, ControlTemplates, Converter) that WPF offers in order to fire up a Tooltip containing all Notifications for an element.</p>
<p>CU next time . . . </p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2009/10/27/notifications-the-wpf-way-i-guess-part-ii/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Notifications the WPF way (I guess), Part I</title>
		<link>http://www.bjoernrochel.de/2009/10/20/notifications-the-wpf-way-i-guess-part-i/</link>
		<comments>http://www.bjoernrochel.de/2009/10/20/notifications-the-wpf-way-i-guess-part-i/#comments</comments>
		<pubDate>Tue, 20 Oct 2009 19:38:09 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/?p=556</guid>
		<description><![CDATA[Update 2.11.2009: I removed the DependencyObject and DependencyProperty references from the ViewModel. The solution works fine without them.
This is the start of a small mini series about how I would currently approach the &#8216;Notification Pattern&#8217; in a WPF application, using the default WPF practices and patterns. Think about it as a step by step guide [...]]]></description>
			<content:encoded><![CDATA[<p><b>Update 2.11.2009: I removed the DependencyObject and DependencyProperty references from the ViewModel. The solution works fine without them.</b></p>
<p>This is the start of a small mini series about how I would currently approach the &#8216;Notification Pattern&#8217; in a WPF application, using the default WPF practices and patterns. Think about it as a step by step guide for using DataBinding, Control-Templates, Styles, Resource-Inheritance, Converters and the Attached-Behavior-Pattern for displaying Notifications in the WPF-UI. (I guess most of this is also doable in Silverlight too, but I&#8217;ve never done anything with SL so I can&#8217;t say for sure). I&#8217;ve also prepared a little bit of sample code for this topic which will be download-able soon.</p>
<p><strong>First,Â  some cautious warnings</strong></p>
<p>I&#8217;m by no means a WPF-expert. I&#8217;m still in the learning phase. So,Â  if there are more obvious or intuitive solutions to the problem, or I&#8217;m plain wrong about this,Â  feel free to comment. I&#8217;m sure there is A LOT room for improvement.</p>
<p><strong>What I&#8217;ve left out intentionally</strong></p>
<p>I tried to strip everything unnecessary for the scope of the post from the code. This includes for instance IoC, Convention over Configuration, Code-Contracts, Expression-based Databinding setup and some base class or extension refactorings. Don&#8217;t get me wrong, I absolutely value those elements, but I wanted the example to be as easy as possible while being somewhat useful for a &#8216;real world&#8217; application. The code might look a bit raw at at some edges because of this. So please keep that in mind before throwing with stones <img src='http://www.bjoernrochel.de/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p><strong>Some other prerequesites</strong></p>
<p>A while back I wrote a post about <a href="http://www.bjoernrochel.de/2009/08/28/implementing-the-notification-pattern-using-dataannotation-validators/">implementing the Notification-pattern using System.Componentmodel.DataAnnotations</a>. It demonstrates the implementation of a generic validator based on the DataAnnotation attributes. Besides that, <a href="http://www.bjoernrochel.de/2009/08/19/the-attached-behavior-pattern/">this</a> post about the Attached-Behavior-Pattern will also be useful for this mini-series. Please give them a short visit if you haven&#8217;t read them yet.</p>
<p><strong>The example scenario</strong></p>
<p>The scenario I&#8217;m going to use for the example is a very simple sign up form. It contains two input fields for username / email and a &#8217;sign-up&#8217; button. It looks like this.</p>
<p><a href="http://www.bjoernrochel.de/wp-content/uploads/2009/10/signup.bmp"><img class="alignnone size-full wp-image-561" src="http://www.bjoernrochel.de/wp-content/uploads/2009/10/signup.bmp" alt="" /></a></p>
<p>Rules associated with the fields are:</p>
<p>1. Username is required and must at least be 5 characters long.<br />
2. Email is required and must contain a valid email address.</p>
<p>If any of the rules is broken, the related element should be visually highlighted . . .</p>
<p><a href="http://www.bjoernrochel.de/wp-content/uploads/2009/10/signupadorner.bmp"><img class="alignnone size-full wp-image-562" src="http://www.bjoernrochel.de/wp-content/uploads/2009/10/signupadorner.bmp" alt="" /></a></p>
<p>. . . and when you hover over the element you&#8217;ll get a detailed description of the error from a tooltip.</p>
<p><a href="http://www.bjoernrochel.de/wp-content/uploads/2009/10/signuptooltip.bmp"><img class="alignnone size-full wp-image-563" src="http://www.bjoernrochel.de/wp-content/uploads/2009/10/signuptooltip.bmp" alt="" /></a></p>
<p>I&#8217;m using the PresentationModel / MVVM pattern for the UI since it seems to be the default UI pattern in WPF.</p>
<p><strong>This is how I would like my SignUpView to be<br />
</strong></p>
<pre class="brush: xml">
&lt;Window x:Class=&quot;Notifications.SignUpView&quot;
    xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
    xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;&gt;
    &lt;Grid&gt;
        &lt;Grid.RowDefinitions&gt;
            &lt;RowDefinition Height=&quot;*&quot;/&gt;
        &lt;/Grid.RowDefinitions&gt;
        &lt;Grid.ColumnDefinitions&gt;
            &lt;ColumnDefinition Width=&quot;*&quot;/&gt;
        &lt;/Grid.ColumnDefinitions&gt;
        &lt;GroupBox
            Grid.Column=&quot;1&quot;
            Grid.Row=&quot;1&quot;
            Header=&quot;Sign up&quot;
            BorderThickness=&quot;2&quot;
            VerticalAlignment=&quot;Center&quot;
            HorizontalAlignment=&quot;Center&quot;
            MaxWidth=&quot;300&quot;
            MaxHeight=&quot;600&quot;&gt;
            &lt;Grid&gt;
                &lt;Grid.RowDefinitions&gt;
                    &lt;RowDefinition /&gt;
                    &lt;RowDefinition /&gt;
                &lt;/Grid.RowDefinitions&gt;
                &lt;Grid.ColumnDefinitions&gt;
                    &lt;ColumnDefinition Width=&quot;Auto&quot;/&gt;
                    &lt;ColumnDefinition Width=&quot;Auto&quot;/&gt;
                    &lt;ColumnDefinition Width=&quot;*&quot;/&gt;
                &lt;/Grid.ColumnDefinitions&gt;
                &lt;Label
                    Content=&quot;Username:&quot;
                    VerticalAlignment=&quot;Bottom&quot;
                    Margin=&quot;10,0,10,0&quot;
                    Grid.Row=&quot;0&quot;
                    Grid.Column=&quot;0&quot; /&gt;
                &lt;Label
                    Content=&quot;Email:&quot;
                    VerticalAlignment=&quot;Bottom&quot;
                    Margin=&quot;0,0,10,0&quot;
                    Grid.Row=&quot;0&quot;
                    Grid.Column=&quot;1&quot; /&gt;
                &lt;TextBox
                    Name=&quot;Username&quot;
                    MinWidth=&quot;100&quot;
                    MaxHeight=&quot;30&quot;
                    Margin=&quot;10,0,10,10&quot;
                    Grid.Row=&quot;1&quot;
                    Grid.Column=&quot;0&quot;
                    TabIndex=&quot;0&quot;
                    Text=&quot;{Binding Path=Username, Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}&quot; /&gt;
                &lt;TextBox
                    Name=&quot;Email&quot;
                    MinWidth=&quot;100&quot;
                    MaxHeight=&quot;30&quot;
                    Margin=&quot;0,0,10,10&quot;
                    Grid.Row=&quot;1&quot;
                    Grid.Column=&quot;1&quot;
                    Text=&quot;{Binding Path=Email, Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}&quot;
                    TabIndex=&quot;1&quot; /&gt;
                &lt;Button
                    MaxHeight=&quot;30&quot;
                    Grid.Row=&quot;1&quot;
                    Margin=&quot;0,0,10,10&quot;
                    Grid.Column=&quot;2&quot;
                    Content=&quot;Sign up!&quot;
                    TabIndex=&quot;3&quot;
                    Command=&quot;{Binding Path=SignUpCommand, Mode=OneWay}&quot; /&gt;
            &lt;/Grid&gt;
        &lt;/GroupBox&gt;
    &lt;/Grid&gt;
&lt;/Window&gt;
</pre>
<p><strong>This is how I would like my SignUpViewModel to be<br />
</strong></p>
<pre class="brush: csharp">
public class SignUpViewModel : INotificationSource
    {
        private readonly NotificationCollection _notifications;
        private readonly DelegateCommand _signUpCommand;
        private readonly ISignUpService _signUpService;
        private readonly IValidator&lt;SignUpViewModel&gt; _validator;

        #region Constructors

        public SignUpViewModel(IValidator&lt;SignUpViewModel&gt; validator, ISignUpService signUpService)
        {
            _validator = validator;
            _signUpService = signUpService;
            _notifications = new NotificationCollection();
            _signUpCommand = new DelegateCommand(TrySignUp);
        }

        #endregion

        #region Properties

        [Required(ErrorMessage = &quot;Field &#039;Username&#039; is missing&quot;)]
        [MinimumStringLength(5)]
        public string Username
        {
            get;
            set;
        }

        [Required(ErrorMessage = &quot;Field &#039;Email&#039; is missing&quot;)]
        [MinimumStringLength(5)]
        public string Email
        {
            get;
            set;
        }

        public ICommand SignUpCommand
        {
            get { return _signUpCommand; }
        }

        public NotificationCollection Notifications
        {
            get { return _notifications; }
        }

        #endregion

        #region Private methods

        private void TrySignUp()
        {
            if (!IsValid())
            {
                return;
            }

            _signUpService.TrySignUp(Username, Email);
        }

        private bool IsValid()
        {
            Notifications.Clear();

            _validator.Validate(this, Notifications);

            return Notifications.ContainsErrors;
        }

        #endregion
    }
</pre>
<p><strong>Did you notice it? </strong></p>
<p>There is NO CODE in the View (Xaml and code behind) or the ViewModel which displays the Notifications.There&#8217;s also no base class for View or ViewModel where the code might be. What&#8217;s there on the other hand is only a collection of Notifications hanging of the ViewModel which is filled by the Validator. You might yourself now ask: Where is the damn glue code?</p>
<p>Yeah I know dumb question because I answered it mostly in the introduction of the post. The interesting thing is that it isn&#8217;t a single location. As you will see the responsibilities for achieving the effect are separated between several components.</p>
<p><strong>In the next posts we&#8217;re going to take a look at </strong></p>
<ul>
<li>how to use the Attached-Behavior-Pattern together with Styles and resource based inheritance in order to match the Notification (s) from the ViewModel to the related FrameworkElements in the logical WPF tree.</li>
<li>how to use a DataTrigger on an Attached Properties in order to setup the Tooltip and showing the red border.</li>
<li>how to bind the Tooltip correctly to the related Notification (s).</li>
</ul>
<p>I hope I made you at least a bit curious . . .</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2009/10/20/notifications-the-wpf-way-i-guess-part-i/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Implementing the Notification Pattern using DataAnnotation Validators</title>
		<link>http://www.bjoernrochel.de/2009/08/28/implementing-the-notification-pattern-using-dataannotation-validators/</link>
		<comments>http://www.bjoernrochel.de/2009/08/28/implementing-the-notification-pattern-using-dataannotation-validators/#comments</comments>
		<pubDate>Fri, 28 Aug 2009 13:38:24 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/?p=509</guid>
		<description><![CDATA[Some weeks ago a friend of mine told me about System.ComponentModel.DataAnnotations. It&#8217;s a relatively new addition to the framework, mainly Asp.net related (mh, was it Mvc or Asp.net Dynamic Data? I&#8217;m sure he told me, but I can&#8217;t remember). Although I&#8217;m more focussed on client side development (WinForms + WPF), what he told me made [...]]]></description>
			<content:encoded><![CDATA[<p>Some weeks ago a friend of mine told me about System.ComponentModel.DataAnnotations. It&#8217;s a relatively new addition to the framework, mainly Asp.net related (mh, was it Mvc or Asp.net Dynamic Data? I&#8217;m sure he told me, but I can&#8217;t remember). Although I&#8217;m more focussed on client side development (WinForms + WPF), what he told me made me curious enough to spend some time with it in order to investigate whether the DataAnnotation framework could be reused for validation in a desktop app.</p>
<p><strong>Background</strong></p>
<p>What I was particulary interested in was whether I could use it in order to implement some sort of declarative validation (for most of the standard cases) on my WPF ViewModels. The usage I wanted to achieve was something similar to the code shown in the next listing.</p>
<pre class="brush: csharp">

public class CustomerViewModel
{
       private IValidator&lt;CustomerViewModel&gt; _validator;
       private NotificationCollection _notifications;

       [Required]
       [MinLenght(3)]
       [DisplayName(&quot;First name&quot;)]
       public string FirstName { get; set; }

       [Required]
       [MinLenght(3)]
       [DisplayName(&quot;Last name&quot;)]
       public string LastName  { get; set; }

       [Required(ErrorMessage=&quot;The field Email address is mandatory&quot;)]
       [ValidEmail]
       [DisplayName(&quot;Email address&quot;)]
       public string EmailAddress { get; set; }

       public CustomerViewModel(IValidator&lt;CustomerViewModel&gt; validator)
       {
              _validator = validator;
              _notifications = new NotificationCollection();
       }

       public NotificationCollection Notifications { get { return _notifications;}}

       public bool IsValid()
       {
              _notifications.Clear();
              _validator.Validate(this, _notifications);
              return _notifications.ContainsErrors;
       }
}
</pre>
<p><strong>Here is what I came up with in order to use the DataAnnotation Validators for this</strong></p>
<p>First of all, some basics. I&#8217;m going to demonstrate a (very simple) implementation of the Notification pattern in this post.  A detailed explanation this pattern is a bit out of scope for this post, but here&#8217;re some excellent resources for that:</p>
<ul type="square">
<li> <a href="http://martinfowler.com/eaaDev/Notification.html">The Notification Pattern</a> by Martin Fowler</li>
<li> <a href="http://codebetter.com/blogs/jeremy.miller/archive/2007/06/13/build-your-own-cab-part-9-domain-centric-validation-with-the-notification-pattern.aspx">Domain centric validation with the Notification Pattern</a> by Jeremy D. Miller</li>
</ul>
<p>We&#8217;re starting with a base class for our Notifications. It&#8217;s a simple abstract class containing a message and a Source property. Besides that it contains an implicit conversion to string.</p>
<pre class="brush: csharp">
public abstract class Notification
{
       private readonly string _message;

       protected Notification() : this(string.Empty, string.Empty)
       {
       }

       protected Notification(string message) : this(string.Empty, message)
       {
              _message = message;
       }

       protected Notification(string source, string message)
       {
              Require.ArgumentNotNull(source, &quot;source&quot;);
              Require.ArgumentNotNull(message, &quot;message&quot;);

              _message = message;
              Source = source;
       }

       public string Source { get; protected set; }

       public override string ToString()
       {
              return _message;
       }

       public static implicit operator string(Notification notification)
       {
              return notification.ToString();
       }
}
</pre>
<p>Error is a simple class derived from Notification, which contains no additional code.</p>
<pre class="brush: csharp">
public class Error : Notification
{
       public Error(string source, string message) : base(source, message) { }

       public Error(string message) : base(message) { }
}
</pre>
<p>I&#8217;ve seen some people implementing the Notification pattern with a single Notification class and an enumeration specifying  the type of the Notification (Error, Warning, Info, etc.) but I prever using classes for this. I think readability is way better (and shorter) using classes. Decide for yourself:</p>
<pre class="brush: csharp">
bool isError = notification is Error;
//versus
bool isError = notification.Severity == Severity.Error;
</pre>
<p>It&#8217;s very rare that you only have to validate one element / property. Mostly we&#8217;re dealing with more than one elment beeing validated. Because of that it&#8217;s useful to have a container or collection for Notifications. This gives you a nice place for some additional functionality.</p>
<pre class="brush: csharp">

public class NotificationCollection : ObservableCollection&lt;Notification&gt;
{
       public bool ContainsErrors
       {
              get { return this.Exists(notification =&gt; notification.IsOfType&lt;Error&gt;()); }
       }

       public bool ContainsWarnings
       {
              get { return this.Exists(notification =&gt; notification.IsOfType&lt;Warning&gt;()); }
       }

       public IEnumerable&lt;Notification&gt; AllNotificationsFor(string nameOfSource)
       {
              return this.Where(notification =&gt; string.Equals(notification.Source, nameOfSource, StringComparison.Ordinal));
       }
}
</pre>
<p>While the first properties are pretty obvious, the last method probably needs some explanation. It finds all notifications for a given source name. The source in my implementation is the name of the property on the ViewModel that was validated. Im currently using a little convention here. Properties in WPF views have the same name as the ViewModel properties they&#8217;re bound to. This makes it relatively easy to correlate those two things (meaning deciding which Notification belongs to which UIElement).</p>
<p>Having set this up, let me walk you through the validator implementation.</p>
<p><strong>A Validator&lt;T&gt; using DataAnnotations</strong></p>
<pre class="brush: csharp">

public class Validator&lt;TElement&gt; : IValidator&lt;TElement&gt;
{
       private static readonly IEnumerable&lt;PropertyValidator&gt; Validators;

       static Validator()
       {
              var properties = typeof (TElement).GetProperties(BindingFlags.Instance | BindingFlags.Public);

              Validators = from property in properties
                     where property.IsMarkedWith&lt;ValidationAttribute&gt;()
                     select new PropertyValidator(property);
       }
</pre>
<p>The static constructor of the Validator class uses reflection to find all marked properties of the target type specified via the generic type argument TElement.  It searches for properties marked at least with one derivate of the System.ComponentModel.DataAnnotations.ValidationAttribute and creates a PropertyValidator for each match.</p>
<pre class="brush: csharp">

#region IValidator&lt;TElement&gt; Members

public void Validate(TElement element, NotificationCollection notifications)
{
       Validators.Each(entry =&gt; entry.Validate(element, notifications));
}

#endregion
</pre>
<p>The actual validation happens inside the Validate method. This method simply uses all known PropertyValidators in order to validate the target object.</p>
<pre class="brush: csharp">

#region Nested type: PropertyValidator

private class PropertyValidator : IValidator
{
       private readonly PropertyInfo _property;
       private readonly string _propertyDisplayName;
       private readonly IEnumerable _propertyValidators;

       public PropertyValidator(PropertyInfo property)
       {
              _property = property;
              _propertyDisplayName = GetDisplayName(_property);
              _propertyValidators = GetValidators(property);
       }
</pre>
<p>A PropertyValidator does some things internally when it&#8217;s created. First it determines the name for the validated element which should be used in the UI. Since you probably don&#8217;t want the user to see something like &#8220;FirstName is required&#8221; or &#8220;SelectedCountry is required&#8221; I&#8217;m using<br />
System.ComponentModel.Design.DisplayNameAttribute here which can be used to specify a UI-friendly name. If no DisplayNameAttribute is specified on a property the validator uses the property name instead.</p>
<pre class="brush: csharp">

private static string GetDisplayName(PropertyInfo property)
{
       if (property.IsMarkedWith&lt;DisplayNameAttribute&gt;())
       {
              return property.GetAttribute&lt;DisplayNameAttribute&gt;().DisplayName;
       }

       return property.Name;
}
</pre>
<p>After it has determined the UI friendly display name it extracts all DataAnnotations ValidationAttributes from the property. (Note: GetAttributes is an ExtensionMethod. Same applies to IsMarkedWith and GetAttribute)</p>
<pre class="brush: csharp">

private static IEnumerable&lt;ValidationAttribute&gt; GetValidators(PropertyInfo property)
{
       return property.GetAttributes&lt;ValidationAttribute&gt;();
}
</pre>
<p>And here is the rest, which brings the whole thing to life. This code simply extracts the value from the property, iterates over all known ValidationAttributes and checks the value with them. When a ValidationAttribute signals that a value is not valid, an error message is formatted with the UI-friendly name I talked earlier about and the whole thing is stored as an Error.</p>
<pre class="brush: csharp">

#region IValidator Members

public void Validate(TElement element, NotificationCollection notifications)
{
       var value = _property.GetValue(element, new object[] {});

       _propertyValidators.Each(validator =&gt;
       {
              if (!validator.IsValid(value))
              {
                     string formmattedErrorMessage = validator.FormatErrorMessage(_propertyDisplayName);
                     notifications.Add(new Error(_property.Name, formmattedErrorMessage));
              }
       });
}

#endregion
</pre>
<p><strong> Bottom line </strong></p>
<p>It&#8217;s pretty easy to combine the existing functionality provided by DataAnnotations with the Notification Pattern. It just took me an hour to get to a working solution which I consider pretty fast and which imho indicates an easy to use framework. As you can imagine the hard part isn&#8217;t getting the Notifications out of the model, but rather finding an unrepetative, intuitive way to display them in the UI. In the past I&#8217;ve missed several times the pit of success regarding this aspect. However I&#8217;m really confident that my current solution is really Dry AND easy to use.</p>
<p>In one of the next posts I&#8217;m going to show how to combine Attached Behavior, Styles and Templates in order to bring the Notifications described in this post to the applications front door, the UI . . .</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2009/08/28/implementing-the-notification-pattern-using-dataannotation-validators/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>The Attached Behavior Pattern</title>
		<link>http://www.bjoernrochel.de/2009/08/19/the-attached-behavior-pattern/</link>
		<comments>http://www.bjoernrochel.de/2009/08/19/the-attached-behavior-pattern/#comments</comments>
		<pubDate>Wed, 19 Aug 2009 06:46:01 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/?p=493</guid>
		<description><![CDATA[With new technologies often completely new patterns emerge as people try to check-out how far a technology might take them. One interesting example for this is the Attached Behavior Pattern which seems to get a lot of attention in the WPF and Silverlight community lately. It&#8217;s a great example of what you can do with [...]]]></description>
			<content:encoded><![CDATA[<p>With new technologies often completely new patterns emerge as people try to check-out how far a technology might take them. One interesting example for this is the Attached Behavior Pattern which seems to get a lot of attention in the WPF and Silverlight community lately. It&#8217;s a great example of what you can do with those technologies that was previously only very hard to achieve (although sometimes in my calm moments it feels a little bit like a hack to me). </p>
<p />
Anyway, here is what the pattern actually does:</p>
<p />
The Attached Behavior Pattern uses the moment when an attached DependencyProperty is attached to a DependencyObject in order to wire event handlers to it. With this you&#8217;re able to extend the behavior of elements in the WPF trees with arbitrary code.</p>
<p />
Let&#8217;s take a look at how this can be achieved. First of all we need a class deriving from DependencyObject in order to be able to provide an attached DependencyProperty. It uses the standard pattern of registering the IsEnabled DependencyProperty in the static constructor (which is a bit clunky, btw).</p>
<pre class="brush: csharp">
    public class MyBehavior : DependencyObject
    {
        public static readonly DependencyProperty IsEnabledProperty;

        static MyBehavior ()
        {
            IsEnabledProperty = DependencyProperty.RegisterAttached(
                &quot;IsEnabled&quot;, //Name of the property
                typeof(bool),//Type of the attached property
                typeof(MyBehavior),//Type of the class that provides the property
                new FrameworkPropertyMetadata(false)); //Default value
        }

        public bool IsEnabled
        {
            get { return this.GetValue&lt;bool&gt;(IsEnabledProperty); }
            set { SetValue(IsEnabledProperty, value); }
        }
    }
</pre>
<p>Pretty standard stuff so far. However you can use another constructor of FrameworkPropertyMetdata in order to supply a callback which is called when the value of the attached property changes.</p>
<pre class="brush: csharp">

	IsEnabledProperty = DependencyProperty.RegisterAttached(
                &quot;IsEnabled&quot;, //Name of the property
                typeof(bool),//Type of the attached property
                typeof(MyBehavior),//Type of the class that provides the property
                new FrameworkPropertyMetadata(false, OnBehaviorEnabled)); //Default value + Callback
</pre>
<p>Next thing we need to do is to configure this attached property on the DependencyObject we want to attach behavior to. This is preferably done in XAML. You&#8217;ve got at least two options for doing the configuration. The first option is to set your attached property in the XAML file of a UserControl, Page or Window directly at the source, the element you want to attach behavior to.</p>
<pre class="brush: xml">

&lt;TextBox myNamespace:MyBehavior.IsEnabled=&quot;true&quot; /&gt;
</pre>
<p>The other option is to use the the power of styles (an area were WPF really shines imho) in order to set it for all elements to which a style is applied.</p>
<pre class="brush: xml">

 &lt;Style TargetType=&quot;TextBox&quot;&gt;
        &lt;Setter Property=&quot;myNamespace:MyBehavior.IsEnabled&quot; Value=&quot;true&quot; /&gt;
 &lt;/Style&gt;
</pre>
<p>Personally I very much vote for the second option, because it enables you to specify the attached behavior in a single place in contrast to configuring it at several places in your solution. Don&#8217;t repeat yourself, unless you really need to. </p>
<p>
Now, fasten your seatbelts. This is were the fun begins. When the WPF / Silverlight infrastructure loads the compiled baml from the resources and builds the element tree from it (and with this attaches our new property to the specified elements) the callback method gets called.</p>
<pre class="brush: csharp">

        private static void OnBehaviorEnabled(
            DependencyObject dependencyObject,
            DependencyPropertyChangedEventArgs args)
        {
            TextBox textBox = (TextBox)dependencyObject;

            textBox.LostFocus += (s,e) =&gt;
            {
	          //Put your little piece of magic here
            };

        }
    }
</pre>
<p>With first parameter of the callback you get a reference to the DependencyObject to which our attached property has been attached to. You&#8217;re now able to wire all sort of event handlers to the DependencyObject and are able to execute arbitrary code when the event occurs. </p>
<p />
Here ends our journey for today. Attached Behaviors is a really nice technique which enabled me to do something that I always wanted to have in my WinForms apps  but never found a satisfiing way to implement it (just a bit patience, I&#8217;m going to blog about it soon). I think it will be interesting to see<br />
how this pattern is used in the future. While new patterns always have the tendency to be overused, I think that this particular pattern can enable lots of valuable things . . .</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2009/08/19/the-attached-behavior-pattern/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>WPF is not WinForms</title>
		<link>http://www.bjoernrochel.de/2009/08/17/wpf-is-not-winforms/</link>
		<comments>http://www.bjoernrochel.de/2009/08/17/wpf-is-not-winforms/#comments</comments>
		<pubDate>Mon, 17 Aug 2009 10:36:45 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/?p=485</guid>
		<description><![CDATA[tttI&#8217;ve been investing a lot of time in learning WPF lately. WPF has always been somehow interesting to me, however I never found actually the time to learn it from the ground up. I&#8217;ve been trying to grok it for several weeks know and am now slowly coming to a point were I can feel [...]]]></description>
			<content:encoded><![CDATA[<p>tttI&#8217;ve been investing a lot of time in learning WPF lately. WPF has always been somehow interesting to me, however I never found actually the time to learn it from the ground up. I&#8217;ve been trying to grok it for several weeks know and am now slowly coming to a point were I can feel the ROI, start seeing the big picture (how the whole WPF architecture fits together) and what&#8217;s the really beneficial side of WPF compared to WinForms.</p>
<p>I&#8217;ve read several times about how steep the learning curve is and must admit, yeah that&#8217;s probably right. At least I&#8217;ve experienced it that way. BUT, here is the interesting side node: That&#8217;s mostly not because of the difficulty or complexity of the technology itself. A lot of my problems arose because of the way how I tried to approach WPF.</p>
<p>Having spend most of my professional work with WinForms seems to have left some traces. I remember lots and lots of situations where I thought to myself: <em>&#8220;Why is that so hard? In WinForms you must simply . . .&#8221;</em>, <em>&#8220;This TreeView just plain sucks&#8221;</em> or <em>&#8220;Mh, where is the Dock property on a Control?&#8221;</em>. Makes me smile now when I think about it. What I basically experienced is <strong>THAT IT&#8217;S HARD TO DO WINFORMS DEVELOPMENT WITH WPF</strong>.</p>
<p>WPF was never designed to be WinForms V2. Neither was it designed to have a similar programming model. After realizing this here is a little yoda-eske advice for WPF-learners like me:</p>
<p><strong>Don&#8217;t let you&#8217;re WinForms knowledge stand in your way. Try to really understand the programming model and the intentions of WPF first and constantly review whether problems you experience while learning WPF come from trying to do the things the way you&#8217;re used to in WinForms.</strong></p>
<p>Once I&#8217;ve understood that I really felt that I made a big leap forward. WPF is such a rich, enjoyable technology if you stick with it long enough. Sadly I&#8217;m currently not participating in a WPF or Silverlight project (like so may others), but I&#8217;ve high hopes.</p>
<p>Better times are coming . . .</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2009/08/17/wpf-is-not-winforms/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
