WPF(1)换肤
1、先准备2套皮肤

2、A.xaml
1 <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 2 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 3 <Style x:Key="Grid_Container" TargetType="Grid"> 4 <Setter Property="Background" Value="red"/> 5 </Style> 6 </ResourceDictionary>
B.xaml
1 <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 2 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 3 <Style x:Key="Grid_Container" TargetType="Grid"> 4 <Setter Property="Background" Value="Green"/> 5 </Style> 6 </ResourceDictionary>
3、建立一个使用皮肤的窗体Window1.xaml
1 <Window x:Class="WpfApp.Window1" 2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 4 Title="Window1" Height="300" Width="300"> 5 <Grid Style="{DynamicResource Grid_Container}"> 6 <Button Content="A" Height="23" HorizontalAlignment="Left" Margin="30,70,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" /> 7 <Button Content="B" Height="23" HorizontalAlignment="Left" Margin="111,70,0,0" Name="button2" VerticalAlignment="Top" Width="75" Click="button2_Click" /> 8 </Grid> 9 </Window>
4、为按钮添加换肤的代码
1 private void button1_Click(object sender, RoutedEventArgs e) 2 { 3 Application.Current.Resources.MergedDictionaries.Clear(); 4 ResourceDictionary resource = (ResourceDictionary)Application.LoadComponent(new Uri("/WpfApp;component/Skin/A/A.xaml", UriKind.Relative)); 5 6 Application.Current.Resources.MergedDictionaries.Add(resource); 7 } 8 9 private void button2_Click(object sender, RoutedEventArgs e) 10 { 11 Application.Current.Resources.MergedDictionaries.Clear(); 12 ResourceDictionary resource = (ResourceDictionary)Application.LoadComponent(new Uri("/WpfApp;component/Skin/B/B.xaml", UriKind.Relative)); 13 14 Application.Current.Resources.MergedDictionaries.Add(resource); 15 }
5、效果
点击A按钮:

点击B按钮

浙公网安备 33010602011771号