JBeagle
JBeagle

Reputation: 2660

Bind WPF Radio Button to RadioButton within ViewModel`

Basically I have a collection of radio buttons on in a User Control. I would like these to be equal to their 'counterparts' which are kept in a list within the ViewModel.

At the moment I have to bind pretty much every property of each one, to the applicable index in the ViewModel's collection of them. E.g:

<RadioButton x:Name="btnStatus2" IsChecked="{Binding Path=radioButtonsIsChecked, Mode=TwoWay}" 
                     Content="{Binding Path=StatusButtonList[1].Content, Mode=TwoWay}"
                     Tag="{Binding Path=StatusButtonList[1].Tag, Mode=TwoWay}"
                     Visibility="{Binding Path=StatusButtonList[1].Visibility, Mode=OneWay}"
                     GroupName="statusBtns" Grid.Column="1" Grid.Row="0" >

As you can see the View is going to be quite large if I have 10 radio buttons in my control. I'm pretty new to WPF and any advice will be greatly appreciated. Thanks!

Upvotes: 0

Views: 956

Answers (1)

kenwarner
kenwarner

Reputation: 29120

Use an ItemsControl and set the ItemsSource property to your collection in the viewmodel.

<ItemsControl ItemsSource="{Binding Path=RadioButtons}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <RadioButton IsChecked="{Binding Path=IsRadioButtonChecked}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

There are also special derived types of ItemsControl in WPF that provide additional features (scrolling, selected items, etc). ListView, ListBox, ComboBox, DataGrid, TreeView, etc are all ItemsControls that you could also use here

Upvotes: 1

Related Questions