WPF:使用命令从 PreviewMouseLeftButtonDown 事件中获取 ListViewIndex

WPF: ListViewIndex from PreviewMouseLeftButtonDown event using command

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

<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;
}

PreviewMouseLeftButtonDown 项目被选中之前被触发,所以这种使用 EventTrigger 的方法是行不通的。

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

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

就 MVVM 而言,这并不比在 XAML 标记中使用 EventTrigger 更糟糕,但是如果您希望能够跨多个视图共享此功能,您可以创建一个 attached behaviour:

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}" />