MVVM模式下附加属性的使用

最近开发的一个项目中我们使用了微软模式实践小组的Prism框架(后续会发布一些学习心得),该框架提供了MVVM模式的一种实践方式。在MVVM模式中View的事件的响应一般通过Command可以实现,在无法使用Command实现时也可以使用附加属性(Attached Properties)实现。下面贴一段代码,用来响应ListView的拖放事件。

在ViewModel中定义附加属性:

public static bool GetHandleDragEvent(DependencyObject obj)
        {
            return (bool)obj.GetValue(HandleDragEventProperty);
        }

        public static void SetHandleDragEvent(DependencyObject obj, bool value)
        {
            obj.SetValue(HandleDragEventProperty, value);
        }

        // Using a DependencyProperty as the backing store for HandleDragEvent.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty HandleDragEventProperty =
            DependencyProperty.RegisterAttached("HandleDragEvent", typeof(bool),
            typeof(***), new UIPropertyMetadata(false, OnHandleDragEvent));

 
        private static void OnHandleDragEvent(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {。。。} 



在View中添加TreeView控件:

<Style x:Key="TreeView" TargetType="TreeView" >
            <Setter Property="viewmodels:***.HandleDragEvent" Value="True" />
            <Setter Property="AllowDrop" Value="True" />
</Style>

<TreeView Width="150" DockPanel.Dock="Right" Style="{StaticResource TreeView}"/>

原文地址:https://www.cnblogs.com/wenjingu/p/2013608.html