【问题标题】:Button in DataGrid RowDetails requires two cliks, workaround breaks double clickDataGrid RowDetails 中的按钮需要两次单击,解决方法会中断双击
【发布时间】:2016-05-12 23:10:27
【问题描述】:

我有一个带有在 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 上检测到双击(这很好),但在双击行本身时未检测到(不是)。

有什么想法吗? 谢谢。

【问题讨论】:

    标签: c# wpf datagrid


    【解决方案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));
            }
        }            
    }
    

    【讨论】:

    • 应该是DataGridCellsPresenter 而不是DataGridDetailsPresenter
    猜你喜欢
    • 1970-01-01
    • 2018-10-30
    • 1970-01-01
    • 2011-09-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多