首页 > 解决方案 > WPF:使用命令的 PreviewMouseLeftButtonDown 事件中的 ListViewIndex

问题描述

我想使用命令ListViewIndex从事件中获取索引:PreviewMouseLeftButtonDown

<ListView Name="ListViewFiles">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="PreviewMouseLeftButtonDown">
            <i:InvokeCommandAction Command="{Binding ListViewItemMouseLeftButtonDownCommand}"
                                   CommandParameter="{Binding ElementName=ListViewFiles, Path=SelectedItem}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</ListView>

代码:

在这里,我有我的ListView,但我找不到获取ListViewItem索引或对象的方法。我尝试SelectedItem但它null

public void Execute(object parameter)
{
    var listView = parameter as ListView;
}

标签: wpflistviewlistviewitem

解决方案


PreviewMouseLeftButtonDown在选择项目之前触发,因此这种使用 an 的方法EventTrigger不起作用。

您可以在视图的代码隐藏中MouseLeftButtonDownEvent使用AddHandler方法和参数将事件处理程序连接到:handledEventsToo

ListViewFiles.AddHandler(ListView.MouseLeftButtonDownEvent, new RoutedEventHandler((ss, ee) => 
{
    (DataContext as YourViewModel).ListViewItemMouseLeftButtonDownCommand.Execute(ListViewFiles.SelectedItem);
}), true);

就 MVVM 而言,这并不比EventTrigger在 XAML 标记中使用 an 更糟糕,但是如果您希望能够在多个视图中共享此功能,则可以创建附加行为

public static class MouseLeftButtonDownBehavior
{
    public static ICommand GetCommand(ListView listView) =>
        (ICommand)listView.GetValue(CommandProperty);

    public static void SetCommand(ListView listView, ICommand value) =>
        listView.SetValue(CommandProperty, value);

    public static readonly DependencyProperty CommandProperty =
        DependencyProperty.RegisterAttached(
        "Command",
        typeof(ICommand),
        typeof(MouseLeftButtonDownBehavior),
        new UIPropertyMetadata(null, OnCommandChanged));

    private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        ListView listView = (ListView)d;

        ICommand oldCommand = e.OldValue as ICommand;
        if (oldCommand != null)
            listView.RemoveHandler(UIElement.MouseLeftButtonDownEvent, (MouseButtonEventHandler)OnMouseLeftButtonDown);

        ICommand newCommand = e.NewValue as ICommand;
        if (newCommand != null)
            listView.AddHandler(UIElement.MouseLeftButtonDownEvent, (MouseButtonEventHandler)OnMouseLeftButtonDown, true);
    }

    private static void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        ListView listView = (ListView)sender;
        ICommand command = GetCommand(listView);
        if (command != null)
            command.Execute(listView.SelectedItem);
    }
}

XAML:

<ListView Name="ListViewFiles" 
    local:MouseLeftButtonDownBehavior.Command="{Binding ListViewItemMouseLeftButtonDownCommand}" />

推荐阅读