WPF 如何将主题应用于使用 MVVM 动态创建的对象

Posted

技术标签:

【中文标题】WPF 如何将主题应用于使用 MVVM 动态创建的对象【英文标题】:WPF How to apply Theme to dynamically created object using MVVM 【发布时间】:2021-10-26 23:55:57 【问题描述】:

我有一个在运行时创建的 StackPanel 中的 RadioButton 列表和一个包含 RadioButton 的 UI 的 ResourceDictionary。我知道如何将主题和 RelayCommand 应用到这样的非动态按钮:

<RadioButton Content="Example Radio Button"
    Style="StaticResource MenuButtonTheme"
    IsChecked="True"
    Command="Binding ContentViewCommand"/>

这是动态堆栈面板的视图:

<StackPanel>
    <ItemsControl ItemsSource="Binding SP">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <RadioButton/>
             </DataTemplate>
        </ItemsControl.ItemTemplate>
   </ItemsControl>
</StackPanel>

视图模型:

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));
        
    

如何将 MenuButtonTheme 应用于动态创建的单选按钮?

【问题讨论】:

【参考方案1】:

想通了,这对我有用:

<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>

【讨论】:

【参考方案2】:

你应该看看这篇文章 -> How to set the style programmatically

然后您应该能够看到 RadioButton 的“样式”。

Tl;博士;

rb.Style = Resources["MenuButtonTheme"] as Style;

【讨论】:

以上是关于WPF 如何将主题应用于使用 MVVM 动态创建的对象的主要内容,如果未能解决你的问题,请参考以下文章

如何将搜索应用于 MVVM (WPF) 中的列表,而无需每次都调用列表值?

WPF MvvM DataGrid 动态列

WPF:如何使用 MVVM 将命令绑定到 ListBoxItem?

如何在 MVVM 中的 UserControl 之间进行通信 - WPF 应用程序

WPF MVVM框架引入

Android MVVM 设计模式示例