MVVM: How to convert this code behind snippet into an AttachedProperty?

137 Views Asked by At

In WPF, I would like to know how to convert code behind into an attached behavior, as this follows the MVVM pattern and is more maintainable and testable.

I have the following xAML which implements a docking manager:

<dxb:BarManager x:Name="MyBarManager"/>

In code behind, I could save the layout to an XML file:

MyBarManager.SaveLayoutToStream(...);

I can also load the layout from an XML file:

MyBarManager.LoadLayoutFromStream(...);

In order to follow the MVVM pattern, I would like to convert this to an attached property, so instead of having code behind, I could bind to a string Test in the ViewModel:

<!-- BarManager is part of the framework, it has methods to save/load layout. -->
<dxb:BarManager x:Name="MyBarManager"
     attached:BarLayoutManagerAttachedProperty.DockLayoutSerialize="{Binding Test}">

What I have tried so far

I used the ReSharper template "dependencyProperty" to create the following attached property, however, there doesn't seem to be a way to hook up any of the calls:

public class BarLayoutManagerAttachedProperty : DependencyObject
{
    public static readonly DependencyProperty DockLayoutSerializeProperty = DependencyProperty.RegisterAttached(
        "DockLayoutSerialize",
        typeof (BarManager),
        typeof (BarLayoutManagerAttachedProperty),
        new PropertyMetadata(default(BarManager)));

    public static void SetDockLayoutSerialize(DependencyObject element, BarManager value)
    {
        element.SetValue(DockLayoutSerializeProperty, value);
    }

    public static BarManager GetDockLayoutSerialize(DependencyObject element)
    {
        return (BarManager) element.GetValue(DockLayoutSerializeProperty);
    }
}
0

There are 0 best solutions below