原文: WPF 用代碼調用dynamic resource動态更改背景 - CSDN部落格
一般dynamic resoource通常在XAML裡調用,如下範例:
<Button Click="Button_Click" Background="{DynamicResource
Theme1}" />
如果在ResourceDictionary定義了很多不同的背景,比如:
<VisualBrush x:Key="Theme1">
<VisualBrush.Visual>
<Viewbox Width="1920" Height="1080">
<Canvas x:Name="PART_Canvas" Width="1920" Height="1080">
<Path Data="F1 M 1920.000,1079.906 L 0.000,1080.000 L 0.000,0.094 L 1920.000,0.000 L 1920.000,1079.906 Z">
<Path.Fill>
<LinearGradientBrush MappingMode="Absolute" StartPoint="959.917,-1324.218" EndPoint="959.916,-55.456">
<LinearGradientBrush.GradientStops>
<GradientStop Offset="0.00" Color="#ff5090cd"/>
<GradientStop Offset="0.66" Color="#ff5090cd"/>
<GradientStop Offset="0.76" Color="#ff5090cd"/>
<GradientStop Offset="0.95" Color="#ff287bbf"/>
<GradientStop Offset="1.00" Color="#ff0067b1"/>
</LinearGradientBrush.GradientStops>
<LinearGradientBrush.Transform>
<MatrixTransform Matrix="1.000,0.000,-0.000,-1.000,0.084,0.631" />
</LinearGradientBrush.Transform>
</LinearGradientBrush>
</Path.Fill>
</Path>
</Canvas></ViewBox></VisualBrush.Visual></VisualBrush>
就可以在codebehind裡,用如下方式動态選擇不同的背景:
this.btn.SetResourceReference(BackgroundProperty, "Theme1");