一、首先在资源字典中定义好样式。
样式:
<!--按钮1样式-->
<Style x:Key="btn1" TargetType="Button">
<Setter Property="Cursor" Value="Hand"/>
<Setter Property="Background" Value="#6B6B6B"/>
<Setter Property="HorizontalAlignment" Value="Left"/>
<Setter Property="Foreground" Value="White"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border Background="{TemplateBinding Background}" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}" CornerRadius="5">
<StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
<TextBlock Text="{TemplateBinding Content}" FontWeight="{TemplateBinding FontWeight}" FontSize="{TemplateBinding FontSize}" TextAlignment="Center" VerticalAlignment="Center" HorizontalAlignment="Center"/>
</StackPanel>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Background" Value="#77BEFF"/>
<Setter Property="Foreground" Value="White"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
二、在App.xaml.cs文件中添加以下代码(注意在App.xaml中不用引用资源字典样式):
/// <summary>
/// App.xaml 的交互逻辑
/// </summary>
public partial class App : Application
{
public static App Instance;
public static String Directory;
public App()
{
Instance = this;
Directory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
}
/// <summary>
/// Dynamically load a style from a file
/// </summary>
public void LoadStyleDictionaryFromFile(string inFileName)
{
if (File.Exists(inFileName))
{
try
{
using (var fs = new FileStream(inFileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
// Read in ResourceDictionary File
var dic = (ResourceDictionary)XamlReader.Load(fs);
// Clear any previous dictionaries loaded
Resources.MergedDictionaries.Clear();
// Add in newly loaded Resource Dictionary
Resources.MergedDictionaries.Add(dic);
}
}
catch (Exception ex)
{
Services.LogHelper.ErrorLog("LoadStyleDictionaryFromFile:",ex);
}
}
}
}
三、在界面的控件中用样式动态绑定的方式绑定样式中的key值:
<Grid Grid.Row="0" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Bottom">
<Button x:Name="One" Content="1" Click="One_Click" Style="{DynamicResource ResourceKey=btn2}"/>
</Grid>
<Grid Grid.Row="0" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Bottom">
<Button x:Name="Two" Click="Two_Click" Content="2" Style="{DynamicResource ResourceKey=btn2}"/>
</Grid>
四、在该界面的后台文件(cs文件)中添加动态加载样式文件:
//stylefile :是资源文件路径
string stylefile = $"{App.Directory}\\{"Dictionary"}\\{"MainNight.xaml"}";
App.Instance.LoadStyleDictionaryFromFile(stylefile);