首先看一下窗口的xaml文档
<Window x:Class="WpfApp1_test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1_test"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800" WindowStartupLocation="CenterScreen">
<Grid>
<Button Name="Button_test" Content="Button" Margin="348,181,348,181" Click="Button_Click"/>
</Grid>
</Window>
在这里我只给他放了一个按钮,现在的工作就是咱们通过动态的方式将按钮的样式给改变。
首先看一下实现结果:
首先这个按钮是个普通的按钮,并没有给他设置任何样式,然后我单击一下这个按钮
这个按钮编程白色的去了,这里我并没有直接通过CS代码去设置按钮的背景颜色属性,而是直接使用代码修改了这个按钮的样式,下面上代码:
这里我在事件中写了一段代码:
var myRes = new ResourceDictionary
{
Source = new Uri(@"C:\Users\76621\source\repos\WpfApp1-test\WpfApp1-test\Style\Button_Style.xaml")
};
var mybtn = myRes["ButtonStyle1"] as Style;
Button_test.Style = mybtn;
就成功实现动态的替换掉样式啦!