In some projects, you may need to dynamically change the template of the control. For example, you can select different themes in the software. The software interface and the style of the control vary under different themes, in this case, you can change the control template to implement the desired functions. The basic method is to use ResourceManager when you click the "Switch topic" button to load the new resource dictionary and use the newly loaded resource dictionary to replace the current resource dictionary. Assume that two different resource dictionary files dictionary1.xaml and dictionary2.xaml exist in the themes Folder: use one of the resource dictionaries in mainpage as the default style file:
<Window.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Themes\Dictionary1.xaml"></ResourceDictionary> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Window.Resources>
The following code switches the resource dictionary in the background:
private void Button_Click_1(object sender, RoutedEventArgs e) { ResourceDictionary newDictionary = new ResourceDictionary(); newDictionary.Source = new Uri("Themes/Dictionary1.xaml", UriKind.RelativeOrAbsolute); this.Resources.MergedDictionaries[0] = newDictionary; } private void Button_Click_2(object sender, RoutedEventArgs e) { ResourceDictionary newDictionary = new ResourceDictionary(); newDictionary.Source = new Uri("Themes/Dictionary2.xaml", UriKind.RelativeOrAbsolute); this.Resources.MergedDictionaries[0] = newDictionary; }
If you do not want the control to apply the default style, you can manually set the control style to NULL: <button content = "Topic 1" style = "{X: null} "horizontalalignment =" Left "verticalalignment =" TOP "width =" 75 "/> another method: directly modify the style and template of the control used, however, make sure that the style or template of the control is referenced as dynamicresource rather than staticresource.