Я пытаюсь создать динамические переключатели и хочу отобразить окно сообщения с выбранным элементом в событии изменения переключателя. Я не очень понимаю, как создать новый обработчик событий с шаблоном MVVM, а также как использовать PropertyChangedEventHandler
.
Вот мой код
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>
Просмотр модели
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;
}