简体   繁体   English

将单选按钮选择与数据网格中的行选择同步

[英]Synchronise Radiobutton Selection with Row selection in a datagrid

I have a RadioButtonTemplateColumn in my datagrid.我的数据网格中有一个 RadioButtonTemplateColumn。 When the radiobutton is clicked, the corresponding row gets selected, but when the row is clicked the corresponding radiobutton is not selected.当单选按钮被点击时,相应的行被选中,但当该行被点击时,相应的单选按钮未被选中。 This leaves the system in a 'confused' state as the radiobutton and row selection are not in sync.这使系统处于“混乱”状态,因为单选按钮和行选择不同步。 Please how do I synchronise them?请问如何同步呢? I have reviewed a similar response but it did not resolve the issue or me.我已经查看了类似的回复,但它没有解决问题或我。

Below is the code I have written:下面是我写的代码:

            <DataGrid.Columns>
                <DataGridTemplateColumn>
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <RadioButton GroupName="Select" IsChecked="{Binding IsSelected, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTextColumn Width="Auto" Header="First Name" Binding="{Binding FirstName}"/>
                <DataGridTextColumn Width="Auto" Header="Last Name" Binding="{Binding LastName}"/>
            </DataGrid.Columns>
        </DataGrid>

The problem is that your binding is invalid.问题是您的绑定无效。 If you use a tool like Snoop Wpf or the live visual tree in Visual Studio, you'll see that your binding isn't working.如果您使用Snoop Wpf 之类的工具或 Visual Studio 中的实时可视化树,您将看到您的绑定不起作用。

The reason why is that your RadioButton is inside a template which has the data context of the data that the grid is bound to - not the DataGridRow .原因是您的RadioButton位于模板内,该模板具有网格绑定到的数据的数据上下文 - 而不是DataGridRow If you update your binding like so, it will work:如果您像这样更新绑定,它将起作用:

IsChecked="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}}, Path=IsSelected, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" 

Essentially, I told the binding to look for IsSelected relative to the DataGridRow higher up in the visual tree.本质上,我告诉绑定在可视化树中查找相对于DataGridRow IsSelected

Another problem is that because you're using a RadioButton it cannot be un-selected when clicking on it.另一个问题是,因为您使用的是RadioButton所以单击它时无法取消选择。 If you want it to act like a toggle, you should use a CheckBox instead.如果您希望它像切换一样工作,则应改用CheckBox

I hope this helps.我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM