我有一个带有RowDetailsTemplate中定义的按钮的DataGrid。问题是,当单击按钮时,DataGrid会使用第一次单击来选择行,因此您需要单击该按钮两次。
我已尝试过此处提供的解决方法:wpf RowDetailsTemplate focus:
XAML:
<DataGrid ItemsSource="{Binding SomeCollection}">
<DataGrid.Resources>
<Style TargetType="DataGridRow">
<EventSetter Event="PreviewMouseLeftButtonDown" Handler="SelectRowDetails"/>
<Setter Property="DetailsVisibility" Value="{Binding HasCanadet, Converter={StaticResource BoolToVis}}"/>Mode=OneWay}"/>
</Style>
</DataGrid.Resources>
...
<DataGrid.RowDetailsTemplate>
<DataTemplate>
...
<Button Command="{Binding SomeCommand}" ... \>
...
</DataTemplate>
</DataGrid.RowDetailsTemplate>
...
<DataGrid>
代码背后:
private void SelectRowDetails(object sender, MouseButtonEventArgs e)
{
var row = sender as DataGridRow;
if (row == null)
{
return;
}
row.Focusable = true;
row.Focus();
var focusDirection = FocusNavigationDirection.Next;
var request = new TraversalRequest(focusDirection);
var elementWithFocus = Keyboard.FocusedElement as UIElement;
if (elementWithFocus != null)
{
elementWithFocus.MoveFocus(request);
}
}
这很好用,但我现在需要在DataGrid的行上检测双击事件。我这样做是通过将InputBindings添加到DataGrid并将SelectedItem作为命令参数传递:
...
<DataGrid.InputBindings>
<MouseBinding MouseAction="LeftDoubleClick" Command="{Binding AnotherCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=SelectedItem}" />
</DataGrid.InputBindings>
...
问题是只在RowDetails上检测到双击(这很好),但是双击行本身(不是)时检测不到。
有什么想法吗? 感谢。
答案 0 :(得分:1)
检查事件的来源是否为 DataGridDetailsPresenter
类型private void SelectRowDetails(object sender, MouseButtonEventArgs e)
{
if(e.Source is DataGridDetailsPresenter) // Like this
{
var row = sender as DataGridRow;
if (row == null)
{
return;
}
row.Focusable = true;
row.Focus();
var elementWithFocus = Keyboard.FocusedElement as UIElement;
if (elementWithFocus != null)
{
elementWithFocus.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
}
}
}