简体   繁体   English

如何在数据网格中获取选定的单选按钮并通过单击行选择单选按钮

[英]How to get selected radiobutton in datagrid and select radiobutton by clicking the row

That's my datagrid: 那是我的数据网格:

SelectHouse.xaml.cs SelectHouse.xaml.cs

<DataGrid x:Name="HousesDataGrid" 
                  ItemsSource="{Binding AvailableHouses}"  
                  AutoGenerateColumns="False" 
                  CanUserAddRows="False"
                  IsReadOnly="True">

    <DataGrid.Columns>

        <DataGridTemplateColumn Header="Select:" Width="60" >
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                <RadioButton 
                    GroupName="GroupHouses" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>

        <DataGridTemplateColumn Header="House" Width="Auto">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Name, Mode=OneWay}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>

</DataGrid>

SelectHouseViewModel: SelectHouseViewModel:

public List<Houses> AvailableHouses
{
    get { return _availableHouses; }
}

I've two problems/questions: 我有两个问题/疑问:

  1. How can I get the selected house in my viewmodel? 如何在我的视图模型中获得所选房屋?
  2. If I want to select row 2, I have to check the radiobutton. 如果要选择第2行,则必须选中单选按钮。 Is it possible to select the radiobutton if I click into any column in row two for example if I click into the column of house in row 2, the radiobutton of row 2 should be selected 如果单击第二行中的任何一列,是否可以选择单选按钮?例如,如果单击第二行中房屋的一列,则应该选择第二行的单选按钮

1) To get the selected row of the DataGrid, just bind it's SelectedItem property to a settable House in your ViewModel a-la SelectedItem={Binding SelectedHouse}, where SelectedHouse is the property in your VM. 1)要获取DataGrid的选定行,只需将其SelectedItem属性绑定到ViewModel中的可设置House a-la SelectedItem = {Binding SelectedHouse},其中SelectedHouse是VM中的属性。

2) Why do you even need a radio-button - is it just to visually re-enforce the row selection? 2)为什么您甚至需要一个单选按钮-仅仅是在视觉上加强行选择? if that's the case, then you'll need to add an IsSelected property to your house VM, and bind the radio-button's IsSelected property to it. 如果是这种情况,则需要将IsSelected属性添加到房屋VM中,并将单选按钮的IsSelected属性绑定到它。 You'll also need to hook into the DataGrid's SelectionChanged event to keep all the state consistent. 您还需要连接到DataGrid的SelectionChanged事件,以使所有状态保持一致。

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

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