I'm trying to make dynamic radio buttons and I want to display a message box with the selected item on radio button change event. I don't really understand how to create a new event handler with MVVM pattern neither how PropertyChangedEventHandler
can be used.
Here is my code
XAML
<StackPanel Grid.Row="2">
<TextBlock Text="Select a Salad"
FontSize="18"
Margin="5" />
<ItemsControl ItemsSource="{Binding Salads}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<RadioButton GroupName="Salads"
Content="{Binding ItemDescription}"
IsChecked="{Binding IsSelected}"
Margin="5,1"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
View Model
public class MainWindowViewModel : INotifyPropertyChanged
{
public MainWindowViewModel()
{
Salads = new Collection<SelectableItem>
{
new SelectableItem { ItemDescription = "Kale Avocado", Id = 1},
new SelectableItem { ItemDescription = "Caesar", Id = 2 },
new SelectableItem { ItemDescription = "Arugula with Goat Cheese", Id = 3, IsSelected = true},
new SelectableItem { ItemDescription = "Garden", Id = 4}
};
}
// Salads
public Collection<SelectableItem> Salads { get; set; }
public SelectableItem SelectedSalad
{
get { return Salads.FirstOrDefault(s => s.IsSelected); }
}
// Property Changed
public event PropertyChangedEventHandler PropertyChanged;
}
SelectableItem Class
public class SelectableItem : INotifyPropertyChanged
{
public string ItemDescription { get; set; }
public bool IsSelected { get; set; }
public int Id { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
}