嘿,我在我的WPF MVVM应用程序中使用DataGrid,就像这样
<DataGrid x:Name="SearchGrid"
...>
<DataGrid.Columns>
<DataGridTemplateColumn Width="Auto" Header="Type">
<DataGridTemplateColumn.CellTemplate>
...
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Width="6*"
Binding="{Binding Reference}"
Header="Reference" />
<DataGridTextColumn Width="9*"
Binding="{Binding Description}"
Header="Description" />
</DataGrid.Columns>
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
<cmd:EventToCommand Command="{Binding Path=SelectElementCommand, Mode=OneWay}" CommandParameter="{Binding SelectedItem, ElementName=SearchGrid}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</DataGrid>
当我双击网格中的一行时,执行'SelectElementCommand',当我点击标题时,行将被排序。到目前为止一切都还可以。但是,当我双击一个标题时,该命令也会被执行。怎么阻止?
感谢您的帮助。
答案 0 :(得分:1)
您可以通过将鼠标DoubleClick EventArgs传递给命令来执行此操作:
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
<cmd:EventToCommand Command="{Binding Path=SelectElementCommand, Mode=OneWay}" PassEventArgsToCommand="True" />
</i:EventTrigger>
</i:Interaction.Triggers>
和相应的SelectElementCommand如下所示:
private RelayCommand<MouseButtonEventArgs> _selectElementCommand;
public RelayCommand<MouseButtonEventArgs> SelectElementCommand
{
get
{
return _selectElementCommand
?? (_selectElementCommand= new RelayCommand<MouseButtonEventArgs>(
(s) =>
{
var dep = s.OriginalSource as DependencyObject;
//go up the treeView until you find the ColumnHeader if existed
while (dep != null && !(dep is DataGridColumnHeader))
{
dep = VisualTreeHelper.GetParent(dep);
}
if (!(dep is DataGridColumnHeader))
//you handler logic
}));
}
}
我不明白为什么你将SelectedItem作为CommandParametre传递,因为你可以简单地将它定义为ViewModel中的属性:
private YourRowType _selectedItem ;
public YourRowType SelectedItem
{
get
{
return _selectedItem;
}
set
{
if (_selectedItem == value)
{
return;
}
_selectedItem = value;
RaisePropertyChanged();
}
}