绑定的DoubleClick命令从DataGrid行至VM [英] Bind DoubleClick Command from DataGrid Row to VM
问题描述
我有一个DataGrid和不喜欢我的解决方法,在我的视图模型为点击(又名选择)排火双击命令。
I have a Datagrid and don't like my workaround to fire a double click command on my viewmodel for the clicked (aka selected) row.
查看:
<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>
视图模型:
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;
}
}
我想摆脱视图相关code(具有依赖对象的可视化树助手)在我看来模式,因为这在某种程度上打破了可测试性。但在另一方面,这种方式我避免有事时用户没有对行,但在例如标题点击。
I want to get rid of the view related code (the one with the dependency object and the visual tree helper) in my view model, as this breaks testability somehow. But on the other hand this way I avoid that something happens when the user doesn't click on a row but on the header for example.
PS:我想在看看附加的行为,但在工作中我不能从SkyDrive中下载,所以建的解决方案是最好的。
PS: I tried having a look at attached behaviors, but I cannot download from Skydrive at work, so a 'built in' solution would be best.
推荐答案
你为什么不干脆用一个commandparameter?
why dont you simply use a commandparameter?
<DataGrid x:Name="myGrd"
ItemsSource="{Binding SearchItems}"
SelectedItem="{Binding SelectedItem}"
SelectionMode="Single"
SelectionUnit="FullRow">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
<cmd:EventToCommand Command="{Binding MouseDoubleClickCommand}"
CommandParameter="{Binding ElementName=myGrd, Path=SelectedItem}" />
</i:EventTrigger>
</i:Interaction.Triggers>
...
</DataGrid>
您的命令是这样的
your command is something like this
public ICommand MouseDoubleClickCommand
{
get
{
if (mouseDoubleClickCommand == null)
{
mouseDoubleClickCommand = new RelayCommand<SearchItem>(
item =>
{
var selectedetitem = item;
}
);
}
return mouseDoubleClickCommand;
}
}
编辑:我现在用这个来代替InteractionTriggers
i now use this instead of InteractionTriggers.
<DataGrid.InputBindings>
<MouseBinding MouseAction="LeftDoubleClick"
Command="{Binding Path=MouseDoubleClickCommand}"
CommandParameter="{Binding ElementName=myGrd, Path=SelectedItem}"/>
</DataGrid.InputBindings>
这篇关于绑定的DoubleClick命令从DataGrid行至VM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!