首页 文章

当SelectionMode设置为Cell时,如何在WPF DataGrid中突出显示一行

提问于
浏览
3

我有一个绑定到WPF应用程序中的DataTable的DataGrid . DataGrid的SelectionUnit必须设置为Cell,但我还想为整行添加一个微妙的突出显示,以便在宽DataGrids上,当用户滚动选定的单元格时,他们仍然可以看到突出显示的行 .

这有点问题,因为DataGridRow的IsSelected属性永远不会设置为true,因为未选中Row,Cell是 .

我不介意它是粘性RowSelector中的小箭头或应用于整行的突出显示 . 只需要某种方式突出显示选择哪一行 .

2 回答

  • 3

    我在这里玩过一点,没什么了不起但是工作版本:

    <Style TargetType="DataGridCell">
           <EventSetter Event="Selected" Handler="EventSetter_OnHandlerSelected"/>
           <EventSetter Event="LostFocus" Handler="EventSetter_OnHandlerLostFocus"/>
        </Style>
    

    这是代码隐藏:

    private void EventSetter_OnHandlerSelected(object sender, RoutedEventArgs e)
        {
            DataGridRow dgr = FindParent<DataGridRow>(sender as DataGridCell);
            dgr.Background = new SolidColorBrush(Colors.Red);
        }
    
        private void EventSetter_OnHandlerLostFocus(object sender, RoutedEventArgs e)
        {
            DataGridRow dgr = FindParent<DataGridRow>(sender as DataGridCell);
            dgr.Background = new SolidColorBrush(Colors.White);
        }
    

    这是获取父级的辅助方法:

    public static T FindParent<T>(DependencyObject child) where T : DependencyObject
        {
            //get parent item
            DependencyObject parentObject = VisualTreeHelper.GetParent(child);
    
            //we've reached the end of the tree
            if (parentObject == null) return null;
    
            //check if the parent matches the type we're looking for
            T parent = parentObject as T;
            if (parent != null)
                return parent;
            else
                return FindParent<T>(parentObject);
        }
    

    它不是MVVM,但考虑到我们只是使用View元素 . 我想这次不是必须的 . 所以基本上,在第一次选择时,你会为行着色,在失去的焦点上,将前一个变为白色并更改新选择的颜色 .

  • 1

    这有效,并且像MVVM一样 . 为了更好的可读性,我使用了ExpressionConverter这是一种令人惊讶的方式,使XAML更具可读性,但更容易出错 . 我还对它做了一些修改以支持mutlibindings,但这是offtopic,你从代码中得到了基本的想法:从行和网格的CurrentCell属性中获取数据上下文,并比较它们是否相同 .

    <DataGrid.Resources>
        <Style TargetType="{x:Type DataGridRow}">
            <Style.Triggers>
                <DataTrigger Value="True">
                    <DataTrigger.Binding>
                        <MultiBinding Converter="{amazing:ExpressionConverter 'x[0] == x[1]'}">
                            <Binding RelativeSource="{RelativeSource Self}" Path="DataContext"></Binding>
                            <Binding ElementName="Grid" Path="CurrentCell" Converter="{amazing:ExpressionConverter 'x.Item'}"></Binding>
                        </MultiBinding>
                    </DataTrigger.Binding>
                    <Setter Property="Background" Value="Red"></Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.Resources>
    

相关问题