WPF从ViewModel绑定到DependencyProperty

时间:2014-04-15 16:38:23

标签: c# wpf mvvm treeview dependency-properties

我正在努力解决WPF DependencyProperty / ViewModel绑定问题。

我将此类作为树视图的辅助类:

public class TreeViewHelper : DependencyObject
{
    private static readonly Dictionary<DependencyObject, TreeViewSelectedItemBehavior> Behaviors = new Dictionary<DependencyObject, TreeViewSelectedItemBehavior>();

    public static object GetSelectedItem(DependencyObject obj)
    {
        return obj.GetValue(SelectedItemProperty);
    }

    public static void SetSelectedItem(DependencyObject obj, object value)
    {
        obj.SetValue(SelectedItemProperty, value);
    }

    // Using a DependencyProperty as the backing store for SelectedItem.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty SelectedItemProperty =
        DependencyProperty.RegisterAttached("SelectedItem", typeof(object), typeof(TreeViewHelper), new UIPropertyMetadata(null, SelectedItemChanged));

    private static void SelectedItemChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        if (!(obj is TreeView))
            return;

        if (!Behaviors.ContainsKey(obj))
            Behaviors.Add(obj, new TreeViewSelectedItemBehavior(obj as TreeView));

        var view = Behaviors[obj];
        view.ChangeSelectedItem(e.NewValue);


    }

    private class TreeViewSelectedItemBehavior
    {
        readonly TreeView _view;
        public TreeViewSelectedItemBehavior(TreeView view)
        {
            _view = view;
            view.SelectedItemChanged += (sender, e) => SetSelectedItem(view, e.NewValue);
        }

        internal void ChangeSelectedItem(object p)
        {
            var item = (TreeViewItem)_view.ItemContainerGenerator.ContainerFromItem(p);
            if(item != null) item.IsSelected = true;
        }
    }
}

我的Treeview以这种方式工作:

<TreeView 
                        SelectedValuePath="Id" 
                        DataContext="{Binding Path=TreeViewModel}" 
                        ItemsSource="{Binding Items}" 
                        Background="{StaticResource SliderThumbBackgroundBrush}" 
                        helpers:TreeViewHelper.SelectedItem="{Binding Path=Items, Mode=TwoWay}">

一切正常,但我的挑战是,当DependencyProperty发生变化时,我如何设法让我的viewmodel知道?

提前致谢。

1 个答案:

答案 0 :(得分:1)

更改UIPropertyMetadata

public static readonly DependencyProperty SelectedItemProperty =
        DependencyProperty.RegisterAttached("SelectedItem", typeof(object), typeof(TreeViewHelper), new UIPropertyMetadata(null, SelectedItemChanged));

FrameworkPropertyMetadata

public static readonly DependencyProperty SelectedItemProperty =
        DependencyProperty.RegisterAttached("SelectedItem", typeof(object), typeof(TreeViewHelper), new FrameworkPropertyMetaData(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, SelectedItemChanged));