Telerik UI for WPF下载30天免费试用

在运行时切换自定义样式与主题

使用以下命令设置主题隐式风格,您可以选择在运行时更改控件的主题,而无需重新创建UI。

合并字典中的资源在资源锁定作用域中占据一个位置,该位置恰好位于它们合并到的主资源字典的作用域中之后。你能做的就是将你的自定义样式隔离在单独的资源字典中,并在每次你改变主题时将它们添加到默认字典之后。

例如,您可以按照以下步骤进行操作:

1.创建一个新的应用程序,并从二进制文件。NoXaml文件夹位于Telerik UI for WPF安装文件夹以及主题程序集:

  • Telerik.Windows.Controls.dll

  • Telerik.Windows.Controls.Input.dll

  • Telerik.Windows.Themes.Office_Black.dll

  • Telerik.Windows.Themes.Office2016.dll

2.中为默认主题添加各自的资源字典App.xaml

例1:合并资源字典

< ResourceDictionary > < ResourceDictionary。MergedDictionaries >     

的资源字典最初合并Office_Black主题。

3.在应用程序的布局根目录中添加一些您选择的控件。还有两个按钮将用于在主题之间切换。

例2:添加按钮以在主题之间切换

       < x按钮:Name = " Office_Black保证金=“5”内容=“Office__Black”点击= " Office_Black_Click " / > < x按钮:Name = " Office2016保证金=“5”内容=“Office2016”点击= " Office2016_Click " / > < / StackPanel > < /网格>
4.现在在不同的资源字典中为不同的主题添加自定义样式CustomStyles_Office_Black.xamlCustomStyles_Office2016.xaml,分别包含在主题项目的文件夹。这些自定义资源字典将具有以下内容:

例3:在单独的资源字典中添加自定义样式

< ResourceDictionary xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation“xmlns: telerik = "http://schemas.telerik.com/2008/xaml/presentation“xmlns: x = "http://schemas.microsoft.com/winfx/2006/xaml">   .

为不同的主题创建单独的资源字典可以方便地对每个主题进行定制。但是,您可以使用单个字典,并且在切换主题时只合并该字典,前提是其中没有任何特定于主题的更改。这些变化将包括任何修改控件模板因为这些不同的主题,并可能导致切换时的错误。

5.将资源字典添加到应用程序的MergedDictionaries集合中:

例4:将字典添加到MergedDictionaries中

< ResourceDictionary。MergedDictionaries >     

注意,您应该替换ProjectName项目的实际名称。

6.然后,在按钮中点击处理程序,我们将清除应用程序资源中的合并字典,并合并来自主题程序集的新资源字典以及自定义资源字典中包含的自定义样式:

例5:单击按钮后清除并合并字典

private void Office_Black_Click(对象发送者,RoutedEventArgs e) {this.MergeDictionaries("Office_Black");} private void Office2016_Click(对象发送者,RoutedEventArgs e) {this.MergeDictionaries("Office2016");} private void mergedictionary (string theme) {application . current . resources . mergedictionary . clear ();Application.Current.Resources.MergedDictionaries。Add(new ResourceDictionary() {Source = new Uri("/Telerik.Windows.Themes."component/Themes/System.Windows。xaml", UriKind.RelativeOrAbsolute)});Application.Current.Resources.MergedDictionaries。Add(new ResourceDictionary() {Source = new Uri("/Telerik.Windows.Themes."+ theme +”;component/Themes/Telerik.Windows.Controls。xaml", UriKind.RelativeOrAbsolute)});Application.Current.Resources.MergedDictionaries。Add(new ResourceDictionary() { Source = new Uri("/Telerik.Windows.Themes." + theme + ";component/Themes/Telerik.Windows.Controls.Input.xaml", UriKind.RelativeOrAbsolute) }); Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary() { Source = new Uri("/ProjectName;component/Themes/CustomStyles_" + theme + ".xaml", UriKind.RelativeOrAbsolute) }); }

请注意,mergedictionary中提供的主题应该与各自的主题程序集的名称相匹配,例如-Expression_DarkOffice2016Touch材料。使用这种方法,您可以切换到任何主题由WPF套件的UI提供。

基于上述代码的结果显示在图1

图1:带有Office_Black和Office2016主题的RadButtons

带有Office_Black和Office2016主题的RadButtons

另请参阅

在本文中
Baidu
map