我有一个 Datagrid,不喜欢我的解决方法在我的 View 模型上为单击(又名选定)行触发双击命令。
看法:
<DataGrid EnableRowVirtualization="True"
ItemsSource="{Binding SearchItems}"
SelectedItem="{Binding SelectedItem}"
SelectionMode="Single"
SelectionUnit="FullRow">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
<cmd:EventToCommand Command="{Binding MouseDoubleClickCommand}" PassEventArgsToCommand="True" />
</i:EventTrigger>
</i:Interaction.Triggers>
...
</DataGrid>
View 模型:
public ICommand MouseDoubleClickCommand
{
get
{
if (mouseDoubleClickCommand == null)
{
mouseDoubleClickCommand = new RelayCommand<MouseButtonEventArgs>(
args =>
{
var sender = args.OriginalSource as DependencyObject;
if (sender == null)
{
return;
}
var ancestor = VisualTreeHelpers.FindAncestor<DataGridRow>(sender);
if (ancestor != null)
{
MessengerInstance.Send(new FindDetailsMessage(this, SelectedItem.Name, false));
}
}
);
}
return mouseDoubleClickCommand;
}
}
我想在我的 View 模型中摆脱与 View 相关的代码(具有依赖对象和可视化树助手的代码),因为这会以某种方式破坏可测试性。但另一方面,这样我避免了当用户没有点击行而是点击标题时发生的事情。
PS:我尝试查看附加行为,但我无法在工作时从 Skydrive 下载,因此最好使用“内置”解决方案。
最佳答案
比这里提出的任何解决方案都简单得多。
我正在使用这个。
<!--
requires IsSynchronizedWithCurrentItem
for more info on virtualization/perf https://stackoverflow.com/questions/9949358/datagrid-row-virtualization-display-issue
-->
<DataGrid ItemsSource="{Binding SearchItems}"
IsSynchronizedWithCurrentItem="True"
AutoGenerateColumns="false" CanUserAddRows="False" CanUserDeleteRows="False" IsReadOnly="True" EnableRowVirtualization="True"
>
<!-- for details on ICollection view (the magic behind {Binding Accounts/} https://marlongrech.wordpress.com/2008/11/22/icollectionview-explained/ -->
<DataGrid.InputBindings>
<MouseBinding
MouseAction="LeftDoubleClick"
Command="{Binding MouseDoubleClickCommand}"
CommandParameter="{Binding SearchItems/}" />
</DataGrid.InputBindings>
</DataGrid>
来自 WPF DataGrid: CommandBinding to a double click instead of using Events
关于wpf - 将 DataGrid 行中的 DoubleClick 命令绑定(bind)到 VM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17419570/