WPF 用DynamicResource动态样式切换

平常在用WPF的时候,还是经常用到资源这个东西的,引用资源的时候一般都会用到StaticResource和DynamicResource来引用资源,关于这两个的区别的话我就不多说了,详情可以去参考:用实例讲DynamicResource与StaticResource的区别。我只是想运用DynamicResource来动态的切换样式。从而达到改变一个界面的模板颜色、样式、位置等等。所以来看一个简单的Demo,首先是XAML:

    <DockPanel>
        <StackPanel DockPanel.Dock="Top">
            <Button Name="button" Background="{DynamicResource buttonColor}" Foreground="{DynamicResource foreGround}" Width="100" Height="20" Margin="10" Content="换颜色" Click="Button_Click_1" />
            <Popup Name="popup" AllowsTransparency="True" StaysOpen="False" PopupAnimation="Slide"
                   Placement="Bottom" PlacementTarget="{Binding ElementName=button}">
                <Border Margin="0,0,10,10">
                    <StackPanel>
                        <Button Click="RectangleBlackButton_Click" Background="Transparent" BorderThickness="0">
                            <Rectangle Width="100" Height="20" Margin="0,5" Fill="Black" />
                        </Button>
                        <Button Click="RectangleGreenButton_Click" Background="Transparent" BorderThickness="0">
                            <Rectangle Width="100" Height="20" Margin="0,5" Fill="Green" />
                        </Button>
                        <Button Click="RectangleBlueButton_Click" Background="Transparent" BorderThickness="0">
                            <Rectangle Width="100" Height="20" Margin="0,5" Fill="Blue" />
                        </Button>
                    </StackPanel>
                </Border>
            </Popup>
        </StackPanel>
    </DockPanel>
View Code

这是一个最简单的Button和一个往下的弹框,因为平常用ComboBox用的太多了,换个popup玩玩。顺便学习一下,好久没用这个东西了,不熟悉的可以多看看popup里面的属性。可以看到我用DynamicResource来引用资源,我想动态切换这个Button的Background和Foreground。所以我新建了一些ResourceDictionary 在里面设置了样式,如下这样:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <SolidColorBrush x:Key="buttonColor" Color="Black" />
    <SolidColorBrush x:Key="foreGround" Color="White" />
</ResourceDictionary>
View Code

这只是一个,其他的可以自己设置,还要在App.xaml设置资源的source,这样才能在前面能够找到。最后如果需要变换ResourceDictionary需要在每个下拉框按钮的Click中来更换Xaml:

private void RectangleBlackButton_Click(object sender, RoutedEventArgs e) {
            Application.Current.Resources.MergedDictionaries[0] = new ResourceDictionary() { Source = new Uri("Black.xaml", UriKind.RelativeOrAbsolute) }; 
        }
View Code

或者写的再好点的话可以把这个写为一个静态类再调用也可以,就不用每次都去像我上面那样写的那么麻烦了。

应广大观众的需求,最后要把图放上去,因为做的比较粗糙,不太好意思放图,算了,丢人就丢人吧。

这样,我就通过了一个小的Demo来实现了动态切换的功能,这个功能是比较好的,在每个ResourceDictionary中,都可以设置同一个界面的样式,再通过按钮来更换,从而达到所谓的“换肤”的功能。最后放上Demo的原程序,例子木有好好整理过,随便看看就可以。

原文地址:https://www.cnblogs.com/socialdk/p/3108185.html