WPF MVVM设计问题

时间:2011-04-11 09:53:52

标签: wpf design-patterns mvvm class-design

在我的视图中,我有一个带有事件“TreeView_MouseLeftButtonDown”的TreeView。如果鼠标点击TreeViewItem它会触发它。如果不是,则取消选择最后一个TreeViewItem。 我的问题是,我应该在代码隐藏中执行此操作还是在viewmodel-class中调用静态方法?你会如何解决这个问题?

The Methode:

private void treeView_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    if (sender != null)
    {
        var treeView = sender as TreeView;
        if (treeView != null && treeView.SelectedItem != null)
            TreeViewHelper.ReturnTreeViewItem(ref treeView, (XmlNode)treeView.SelectedItem).IsSelected = false;
    }
} 

XAML:

<TreeView ... KeyDown="TreeView_KeyDown" 
              MouseLeftButtonDown="TreeView_MouseLeftButtonDown" 
              SelectedItemChanged="TreeView_SelectedItemChanged" />

2 个答案:

答案 0 :(得分:2)

您正在尝试向TreeView添加行为

我实现此方法的方法是使用附加属性。我将创建一个名为VerifiesLeftClick或类似的附加属性,并在那里实现逻辑。这样您就不需要后面代码中的事件了。

请参阅here了解样本。

答案 1 :(得分:0)

我使用附加行为为您制作了解决方案,这些行为在Introduction to Attached Behaviors in WPF by Josh Smith

中得到了很好的描述

我的解决方案:

public static class TreeViewBehavior
{
    public static bool GetIsResetMouseLeftButtonDown(TreeView treeView)
    {
        return (bool)treeView.GetValue(IsResetMouseLeftButtonDownProperty);
    }
    public static void SetIsResetMouseLeftButtonDown(TreeView treeViewItem, bool value)
    {
        treeViewItem.SetValue(IsResetMouseLeftButtonDownProperty, value);
    }
    public static readonly DependencyProperty IsResetMouseLeftButtonDownProperty =
        DependencyProperty.RegisterAttached("PreviewMouseLeftButtonDown", typeof(bool), typeof(TreeViewBehavior),
        new UIPropertyMetadata(false, OnIsMouseLeftButtonDownChanged));
    static void OnIsMouseLeftButtonDownChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e)
    {
        TreeView item = depObj as TreeView;
        if (item == null)
            return;
        if (e.NewValue is bool == false)
            return;

        if ((bool)e.NewValue)
        {
            item.PreviewMouseLeftButtonDown += OnMouseLeftButtonDown;
        }
        else
        {
            item.MouseLeftButtonDown -= OnMouseLeftButtonDown;
        }
    }
    static void OnMouseLeftButtonDown(object sender, RoutedEventArgs e)
    {
        var tempItem = e.Source as TreeViewItem;
        if (tempItem != null && tempItem.IsSelected == false)
        {
            tempItem.IsSelected = true;
        }
        else
        {
            var tree = e.Source as TreeView;
            if (tree != null && tree.SelectedItem != null)
            {
                var selItem = (tree.SelectedItem as TreeViewItem);
                if (selItem != null)
                {
                    selItem.IsSelected = false;
                }
            }
        }
    }
}

然后在View中你应该添加:

<TreeView local:TreeViewBehavior.IsResetMouseLeftButtonDown="True">

我希望我的解决方案能够实现您想要实现的目标。