简体   繁体   中英

Allow only one radio button to be checked in a WPF datagird

My datagrid is bound to an observable collection, The datagrid has two columns - one for radio buttons, another to display names. At the moment, I am able to make multiple selections on the datagrid, But my requirement is to select only one radio button at a time such that the selected radio button should notify the viewmodel about the selected user name. How can i achieve it ?

Here's what I tried:

<DataGrid Width="{Binding ActualWidth, ElementName=panel}" 
                              ItemsSource="{Binding obvUsers}"                           
                              Height="390" >                                                                                                                                                                        
                        <DataGrid.Columns>                            
                            <DataGridTemplateColumn Header="" Width="100">
                                <DataGridTemplateColumn.CellTemplate>
                                    <DataTemplate>
                                        <RadioButton IsChecked="{Binding IsUserSelected}"                                    
                                    </DataTemplate>
                                </DataGridTemplateColumn.CellTemplate>
                            </DataGridTemplateColumn>
                            <DataGridTemplateColumn Header="Name">
                                <DataGridTemplateColumn.CellTemplate>
                                    <DataTemplate>
                                        <TextBlock Text="{Binding UserName}" />
                                    </DataTemplate>
                                </DataGridTemplateColumn.CellTemplate>
                            </DataGridTemplateColumn>                
                        </DataGrid.Columns>                       
                    </DataGrid>

Just put a GroupName for your RadioButton . All RadioButton in DataGrid should have a single selection because they have the same group. This works for me.

<DataGridTemplateColumn Header="" Width="100">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <RadioButton GroupName="abc" IsChecked="{Binding IsUserSelected}">
            </RadioButton>                                    
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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