wpf - 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;
}
解决方案
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}" />
推荐阅读
- c++ - C ++ Winsock2客户端未通过远程IP连接到服务器
- php - Windows 中的 Xampp PHP7 和 PHP5
- javascript - Vue 在 10 秒后导航到下一条路线
- html - 重新提交表单后,如何用用户的评论重新填充文本区域?(使用 HTML 和 PHP)
- unity3d - 如何统一获得从白日梦控制器到指向游戏对象的距离?
- swift - NSTextView 仅在当前滚动到底部时才滚动到底部?
- c++ - C++ 中的文件处理:更新一行
- python - 如何为 python cartopy 几何设置偏移量?
- apache - 有什么方法可以拆分 apache2 中的根路径和其他路径?
- android - 单击android自定义键盘中的表情符号键时如何显示表情符号键盘?