WPF 用代码调用dynamic resource动态更改背景 - CSDN博客

原文: 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");


猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/9075342.html