Silverlight 4 Databound CheckBoxList and RadioButtonList Controls to ViewModel


 image

The answer is to use the ItemsControl and the ItemsControl.ItemTemplate property. 

<ItemsControl x:Name="m_itemsControl" ItemsSource="{Binding}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <CheckBox Content="{Binding Text}" IsChecked="{Binding IsSelected, Mode=TwoWay}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Provide a ViewModel with a Collection of Child ViewModel Type that implements INotifyPropertyChanged that will be associated with each CheckBox/RadioButton. The Child ViewModel Type will look like this:

public class SelectableItem : INotifyPropertyChanged
{
    bool IsSelected { get; set; }
    string Text { get; set; }
    string Value { get; set; }       

    …
}

// You can also use an interface for an extra layer of abstraction too.

This class provides the Text to display in the list and also a boolean value to display whether the item is selected or not. 

Click here to download the source code.

Via http://blog.benday.com/archive/2010/08/02/23283.aspx

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s