【问题标题】:How can I let my DataGrid rows be highlighted only if selected by CheckBox?如何让我的 DataGrid 行仅在被 CheckBox 选中时突出显示?
【发布时间】:2017-04-07 21:45:47
【问题描述】:

我有以下数据网格:

<DataGrid x:Name="TheList" Grid.Row="1" ItemsSource="{Binding People}" SelectionMode="Extended" SelectionUnit="FullRow" AutoGenerateColumns="False" 
    <DataGrid.Columns>
        <DataGridCheckBoxColumn Binding="{Binding IsSelected}">
            <DataGridCheckBoxColumn.HeaderTemplate>
                <DataTemplate>
                    <CheckBox IsChecked="{Binding Path=DataContext.AllSelected, RelativeSource={RelativeSource AncestorType=DataGrid}}"></CheckBox>
                </DataTemplate>
            </DataGridCheckBoxColumn.HeaderTemplate>
        </DataGridCheckBoxColumn>
        <DataGridTextColumn Binding="{Binding GivenName}" Header="Given Name" />
        ...
        <DataGridTextColumn Binding="{Binding BranchName}" Header="Branch" />
    </DataGrid.Columns>
</DataGrid>

我更喜欢使用 CheckBox 进行选择,因为它提供了 - 我认为 - 对所选择的内容更清晰、更积极的用户反馈。

我现在的问题是,如果我单击一行,该行以蓝色突出显示,但在该行的项目中,IsSelected 属性仍然为 false。很明显它没有被选中,因为复选框未被选中。

如果我单击一个复选框,我必须单击两次,第一次选择该行作为“活动行”,第二次单击以选中复选框。然后我可以再次单击该行,它不再突出显示,但很明显,由于选中了该复选框,该行被选中。

这在我的用户体验中造成了某种不和谐。我希望单击一行不会突出显示它,但是当我选中它的复选框时,它会突出显示。

我能做到这一点,如何做到这一点?如果没有,在最坏的情况下,我想关闭 DataGrid's 自己的行选择,并且没有突出显示的行,只有选中或未选中的复选框。

【问题讨论】:

  • 绑定到被选中的datagridrow。
  • @Nkosi,我完全不明白你的意思? CheckBox 已经绑定到行内容的 IsSelected 属性,但我无法找到如何绑定到行元素本身的“IsSelected”。

标签: wpf xaml checkbox data-binding datagrid


【解决方案1】:

在当前版本中,复选框绑定到行中对象的IsSelected 属性。

这就是我说绑定到DataGridRowIsSelected 时所指的。

<DataGrid x:Name="TheList" Grid.Row="1" ItemsSource="{Binding People}" SelectionMode="Extended" SelectionUnit="FullRow" AutoGenerateColumns="False" 
    <DataGrid.Columns>
        <DataGridCheckBoxColumn Binding="{Binding Path=IsSelected, RelativeSource={RelativeSource AncestorType=DataGridRow}}">
            <DataGridCheckBoxColumn.HeaderTemplate>
                <DataTemplate>
                    <CheckBox IsChecked="{Binding Path=DataContext.AllSelected, RelativeSource={RelativeSource AncestorType=DataGrid}}"></CheckBox>
                </DataTemplate>
            </DataGridCheckBoxColumn.HeaderTemplate>
        </DataGridCheckBoxColumn>
        <DataGridTextColumn Binding="{Binding GivenName}" Header="Given Name" />
        ...
        <DataGridTextColumn Binding="{Binding BranchName}" Header="Branch" />
    </DataGrid.Columns>
</DataGrid>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-31
    • 2013-12-20
    • 1970-01-01
    • 2013-06-07
    • 2013-06-11
    • 2011-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多