Sunday, June 22, 2014

Creating Dynamic Radio Button Controls in Silverlight MVVM model

There was a need to create dynamic "Radio Button" controls in one of my projects. This was a Silverlight MVVM project.

Since the "View" is isolated from "ViewModel" and connected only through binding, it was not clear on how to do this task.

After few research I found the answer.

This is the code that needs to go on the XAML side. Note the "ItemsControl" element. The itemssource will take in a List of RadioButtonClass.

<Grid DataContext="{StaticResource ViewModel}">
        <StackPanel>
            <ItemsControl ItemsSource="{Binding RadioButtonClassList}">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <RadioButton GroupName="OneGroup" IsChecked="{Binding IsSelected}" Content="{Binding RadioButtonName}"></RadioButton>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        </StackPanel>
 </Grid>


Note the binding properties (IsSelected and RadioButtonName) in the "RadioButton" control.

The "RadioButtonClass" can be defined something like this.

public class RadioButtonClass : INotifyPropertyChanged
{
   public string RadioButtonName;
   public bool IsSelected;
}

In the "ViewModel" class if you add a property which is a List like this List<RadioButtonClass> and bind it to the View as shown in the above XAML snippet (<Grid DataContext="{StaticResource ViewModel}">) then the RadioButtons will show up. The number or radio buttons is equal to the number of items in the List.

Hope this tip helps.

Happy Coding !


 

No comments:

Post a Comment

All Blogs so far ...