Wpf MVVM:如何将此代码隐藏片段转换为AttachedProperty?

Wpf MVVM:如何将此代码隐藏片段转换为AttachedProperty?,wpf,mvvm,dependency-properties,attached-properties,attachedbehaviors,Wpf,Mvvm,Dependency Properties,Attached Properties,Attachedbehaviors,在WPF中,我想知道如何将代码转换为附加行为,因为这遵循MVVM模式,并且更易于维护和测试 我有以下xAML,它实现了停靠管理器: <dxb:BarManager x:Name="MyBarManager"/> 我还可以从XML文件加载布局: MyBarManager.SaveLayoutToStream(...); MyBarManager.LoadLayoutFromStream(...); 为了遵循MVVM模式,我想将其转换为一个附加属性,因此我可以绑定到ViewMode

在WPF中,我想知道如何将代码转换为附加行为,因为这遵循MVVM模式,并且更易于维护和测试

我有以下xAML,它实现了停靠管理器:

<dxb:BarManager x:Name="MyBarManager"/>
我还可以从XML文件加载布局:

MyBarManager.SaveLayoutToStream(...);
MyBarManager.LoadLayoutFromStream(...);
为了遵循MVVM模式,我想将其转换为一个附加属性,因此我可以绑定到ViewModel中的字符串测试,而不是代码隐藏:

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

在代码隐藏中,您有自己的方法。对于xaml,您需要附加属性。有些事情你需要重新考虑。也许你需要附加的事件或行为?你读过这个吗@二元体。是的,你可能是对的。本质上,如果我读取绑定属性测试,我希望它调用方法.LoadLayoutToStream,如果我写入绑定属性测试,我希望它调用方法.SaveLayoutToStream。我不确定哪种方法有效。你能更详细地解释一下你的用例吗?什么时候需要保存和加载布局?我想我现在明白了。您希望通过绑定将当前布局传递给视图,以便加载布局,这没有问题,并且是视图到视图模型绑定的常见任务;您希望从视图模型内部触发的视图中获取当前布局,但使用相同的绑定,并且仅使用它。这是不可能的,因为您的视图模型不能也不应该知道是否存在任何绑定。可以在视图模型中使用事件向视图发出需要布局字符串的信号。顺便说一句,您附加的属性是错误的:您无法将BarManager绑定到字符串。。。
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);
    }
}