WPF换肤
style1.xaml:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style x:Key="BtnStyle" TargetType="{x:Type Button}">
<Setter Property="Background" Value="Blue"/>
</Style>
</ResourceDictionary>
style2.xaml:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style x:Key="BtnStyle" TargetType="{x:Type Button}">
<Setter Property="Background" Value="Yellow"/>
</Style>
</ResourceDictionary>
前台:
<Window x:Class="WpfMarquee.Window5"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window5" Height="300" Width="300">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/WpfMarquee;Component/style1.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid >
<Button Name="Button1" Style="{StaticResource BtnStyle}" />
<Button Name="Button2" Click="button2_Click" />
</Grid>
</Window>
后台:
private void button2_Click(object sender, RoutedEventArgs e)
{
string packUri = @"/WpfMarquee;Component/style2.xaml";
ResourceDictionary myResourceDictionary = Application.LoadComponent(new Uri(packUri, UriKind.Relative)) as ResourceDictionary;
this.Resources.MergedDictionaries.Add(myResourceDictionary);
}
问题:Button1变不了黄色!
------解决方案--------------------复制一份系统Button的默认模板,在模板里面改其背景的颜色吧。
------解决方案--------------------首先直接把样式放到当前页面的资源中,看看button1能不能改变样式,若改变,才能保证你这个样式是写的正确的。
而后看下你的后台带式是否正确的添加到资源中。
最后Button1.UpdateLayout(),试试。