I have a list of RadioButtons in a StackPanel that are created at runtime and a ResourceDictionary that contains the UI for a RadioButton. I know how to apply a theme and RelayCommand to a non-dynamic button like this:
<RadioButton Content="Example Radio Button"
Style="{StaticResource MenuButtonTheme}"
IsChecked="True"
Command="{Binding ContentViewCommand}"/>
Here is the View for the dynamic stack panel:
<StackPanel>
<ItemsControl ItemsSource="{Binding SP}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<RadioButton/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
The ViewModel:
class ContentViewModel : ObservableObject
{
private int numScripts;
private ObservableCollection<RadioButton> _sp;
public ObservableCollection<RadioButton> SP
{
get { return _sp; }
set { _sp = value; }
}
public ContentViewModel()
{
numScripts = 5; // this will not always be 5
_sp = new ObservableCollection<RadioButton>();
CreateRadioButtons(numScripts);
}
public void CreateRadioButtons(int n)
{
for (int i = 0; i < n; i++)
{
RadioButton rb = new()
{
Content = "Radiobutton",
Foreground = Brushes.AntiqueWhite
};
SP.Add(rb);
}
}
}
class ObservableObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
How can I apply MenuButtonTheme to the dynamically created radio buttons?