Maddy
Maddy

Reputation: 590

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

That's my datagrid:

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:

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. 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

Upvotes: 0

Views: 1770

Answers (1)

Andrew
Andrew

Reputation: 1492

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.

2) Why do you even need a radio-button - is it just to visually re-enforce the row selection? 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. You'll also need to hook into the DataGrid's SelectionChanged event to keep all the state consistent.

Upvotes: 2

Related Questions