WPF/MVVM - 如何在ViewModel中双击TreeViewItems?

And*_*uul 29 c# wpf mvvm mouseevent commandbinding

(注-这是一个重新出任我的第一个问题,下得了错误标题发布:这里对不起!)

我有一个标准的WPF树视图,并有绑定项目来查看模型类.

我现在希望在双击项目时处理行为(打开文档visual-studio-style).

我可以在树视图(显示xaml)的控件中触发事件处理程序,但是如何绑定到视图模型类上的特定行为 - 例如ProjectViewModel?

最好绑定到ICommand-implementationmen,因为这在别处使用...

<TreeView ItemsSource="{Binding Projects}" MouseDoubleClick="TreeView_MouseDoubleClick">
    <TreeView.ItemContainerStyle>
        <!-- 
This Style binds a TreeViewItem to a TreeViewItemViewModel. 
-->
        <Style TargetType="{x:Type TreeViewItem}">
            <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
            <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
            <Setter Property="FontWeight" Value="Normal" />
            <Style.Triggers>
                <Trigger Property="IsSelected" Value="True">
                    <Setter Property="FontWeight" Value="Bold" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </TreeView.ItemContainerStyle>

    <TreeView.Resources>
        <HierarchicalDataTemplate DataType="{x:Type Implementations:ProjectViewModel}" ItemsSource="{Binding Children}">
            <StackPanel Orientation="Horizontal">
                <Image Width="16" Height="16" Margin="3,0" Source="Images\Region.png" />
                <TextBlock Text="{Binding DisplayName}" />
            </StackPanel>
        </HierarchicalDataTemplate>

        <HierarchicalDataTemplate DataType="{x:Type Implementations:PumpViewModel}" ItemsSource="{Binding Children}">
            <StackPanel Orientation="Horizontal">
                <Image Width="16" Height="16" Margin="3,0" Source="Images\State.png" />
                <TextBlock Text="{Binding Name}" />
            </StackPanel>
        </HierarchicalDataTemplate>

        <DataTemplate DataType="{x:Type Implementations:PumpDesignViewModel}">
            <StackPanel Orientation="Horizontal">
                <Image Width="16" Height="16" Margin="3,0" Source="Images\City.png" />
                <TextBlock Text="{Binding Name}" />
            </StackPanel>
        </DataTemplate>
    </TreeView.Resources>
</TreeView>
Run Code Online (Sandbox Code Playgroud)

Fre*_*lad 55

稍微更新我的答案.

我已经尝试了很多不同的方法,我仍然觉得附加行为是最好的解决方案.尽管在开始时它可能看起来很多开销但实际上并非如此.我将所有行为保留ICommands在同一个地方,每当我需要支持另一个事件时,只需复制/粘贴并更改事件即可PropertyChangedCallback.

我还添加了可选的支持CommandParameter.

在设计师中,只需选择所需的事件即可

在此输入图像描述

您可以在设置这个TreeView,TreeViewItem或者你喜欢的任何其他地方.

例.把它设置在TreeView

<TreeView commandBehaviors:MouseDoubleClick.Command="{Binding YourCommand}"
          commandBehaviors:MouseDoubleClick.CommandParameter="{Binding}"
          .../>
Run Code Online (Sandbox Code Playgroud)

例.设置它TreeViewItem

<TreeView ItemsSource="{Binding Projects}">
    <TreeView.ItemContainerStyle>
        <Style TargetType="{x:Type TreeViewItem}">
            <Setter Property="commandBehaviors:MouseDoubleClick.Command"
                    Value="{Binding YourCommand}"/>
            <Setter Property="commandBehaviors:MouseDoubleClick.CommandParameter"
                    Value="{Binding}"/>
        </Style>
    </TreeView.ItemContainerStyle>
</TreeView>
Run Code Online (Sandbox Code Playgroud)

这是附加行为 MouseDoubleClick

public class MouseDoubleClick
{
    public static DependencyProperty CommandProperty =
        DependencyProperty.RegisterAttached("Command",
        typeof(ICommand),
        typeof(MouseDoubleClick),
        new UIPropertyMetadata(CommandChanged));

    public static DependencyProperty CommandParameterProperty =
        DependencyProperty.RegisterAttached("CommandParameter",
                                            typeof(object),
                                            typeof(MouseDoubleClick),
                                            new UIPropertyMetadata(null));

    public static void SetCommand(DependencyObject target, ICommand value)
    {
        target.SetValue(CommandProperty, value);
    }

    public static void SetCommandParameter(DependencyObject target, object value)
    {
        target.SetValue(CommandParameterProperty, value);
    }
    public static object GetCommandParameter(DependencyObject target)
    {
        return target.GetValue(CommandParameterProperty);
    }

    private static void CommandChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
    {
        Control control = target as Control;
        if (control != null)
        {
            if ((e.NewValue != null) && (e.OldValue == null))
            {
                control.MouseDoubleClick += OnMouseDoubleClick;
            }
            else if ((e.NewValue == null) && (e.OldValue != null))
            {
                control.MouseDoubleClick -= OnMouseDoubleClick;
            }
        }
    }

    private static void OnMouseDoubleClick(object sender, RoutedEventArgs e)
    {
        Control control = sender as Control;
        ICommand command = (ICommand)control.GetValue(CommandProperty);
        object commandParameter = control.GetValue(CommandParameterProperty);
        command.Execute(commandParameter);
    }
}
Run Code Online (Sandbox Code Playgroud)


Dam*_*cus 9

我迟到了,但我只是使用了不同的解决方案.再一次,它可能不是最好的,但这就是我如何做到这一点.

首先,来自Meleak的前一个答案很酷,但我觉得被迫添加AttachedBehaviors只是为了像MouseDoubleClick一样基本的东西是非常沉重的.这将迫使我在我的应用程序中使用新模式,甚至会使一切变得更复杂.

我的目标是尽可能保持简单.因此我做了一些非常基本的事情(我的例子是针对DataGrid,但你可以在很多不同的控件上使用它):

<DataGrid MouseDoubleClick="DataGrid_MouseDoubleClick">
   <!-- ... -->
</DataGrid>
Run Code Online (Sandbox Code Playgroud)

在代码隐藏中:

private void DataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    //Execute the command related to the doubleclick, in my case Edit
    (this.DataContext as VmHome).EditAppCommand.Execute(null);
}
Run Code Online (Sandbox Code Playgroud)

为什么我觉得它没有打破MVVM模式?因为在我看来,你应该把在唯一的东西代码隐藏的桥梁您的视图模型,事情非常具体到您的UI.在这种情况下,它只是说,如果你双击,激活相关的命令.它几乎与Command ="{Binding EditAppCommand}"相同,我只是模拟了这种行为.

请随意向我发表您对此的看法,我很高兴听到一些批评者对这种思维方式的看法,但是现在我相信这是在不破坏MVVM的情况下实现它的最简单方法.


Ste*_*pUp 6

这真的很简单,这就是我在 TreeView 上处理双击的方式:

<Window x:Class="TreeViewWpfApplication.MainWindow"
    ...
    xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
    ...>

      <TreeView ItemsSource="{Binding Departments}" >
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="MouseDoubleClick">
                <ei:CallMethodAction MethodName="SomeMethod" TargetObject="{Binding}"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>
      </TreeView>
</Window>
Run Code Online (Sandbox Code Playgroud)

System.Windows.Interactivity.dll取自 C:\Program Files (x86)\Microsoft SDKs\Expression\Blend.NETFramework\v4.0\Libraries\System.Windows.Interactivity.dll 或NuGet

我的视图模型:

public class TreeViewModel : INotifyPropertyChanged
{   
    private List<Department> departments;
    public TreeViewModel()
    {
        Departments = new List<Department>()
        {
            new Department("Department1"),
            new Department("Department2"),
            new Department("Department3")
        };
    }

    public List<Department> Departments
    {
        get
        {
            return departments;
        }
        set
        {
            departments = value;
            OnPropertyChanged("Departments");
        }
    }

    public void SomeMethod()
    {
        MessageBox.Show("*****");
    }
}   
Run Code Online (Sandbox Code Playgroud)


小智 5

无论Meleak和伊戈尔的建议是伟大的,但是当双击事件处理程序绑定到TreeViewItem那么事件处理程序要求所有项目的父元素(而不仅仅是点击元素).如果不需要,还有另外一个补充:

private static void OnMouseDoubleClick(object sender, RoutedEventArgs e)
{
    Control control = sender as Control;
    ICommand command = (ICommand)control.GetValue(CommandProperty);
    object commandParameter = control.GetValue(CommandParameterProperty);

    if (sender is TreeViewItem)
    {
        if (!((TreeViewItem)sender).IsSelected)
            return;
    }

    if (command.CanExecute(commandParameter))
    {
        command.Execute(commandParameter);
    }
}
Run Code Online (Sandbox Code Playgroud)