1

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?

sbrownCD
  • 21
  • 3

2 Answers2

1

Figured it out, this is what worked for me:

<StackPanel Grid.Row="1">
    <ItemsControl ItemsSource="{Binding SP}" x:Name="sp_itemsControl">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <DataTemplate.Resources>
                    <Style TargetType="RadioButton" BasedOn="{StaticResource MenuButtonTheme}"/>
                </DataTemplate.Resources>
                <RadioButton Content="{Binding Content}"
                             Foreground="{Binding Foreground}"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</StackPanel>
sbrownCD
  • 21
  • 3
0

You should take a look at this post -> How to set the style programmatically

You should then be able to see the "Style" of the RadioButton.

Tl;dr;

rb.Style = Resources["MenuButtonTheme"] as Style;
newky2k
  • 419
  • 5
  • 12