学海无涯

导航

资源字典 ResourceDictionary

1.在项目上点右键,添加 ”资源字典WPF“ ,命名为:ButtonStyle.xaml

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style x:Key="DefaultButtonStyle" TargetType="Button">
        <Setter Property="Foreground" Value="Blue"/>
        <Setter Property="FontSize" Value="15"/>
    </Style>
    <SolidColorBrush x:Key="solidColor" Color="Red"/>
</ResourceDictionary>

 2. 在 App.xaml 中声明合并自己添加的资源字典

 <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="ButtonStyle.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>

 3.在WPF窗口中使用

<Grid>
        <StackPanel>
            <Button Style="{StaticResource DefaultButtonStyle}" Content="Update" Click="Button_Click"/>
            <Button BorderBrush="{StaticResource solidColor}" Height="40" BorderThickness="5" Content="Button1" Margin="10"/>
            <Button BorderBrush="{DynamicResource solidColor}" Height="40" BorderThickness="5" Content="Button2" Margin="10"/>
        </StackPanel>
    </Grid>

  

 private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.Resources["solidColor"] = new SolidColorBrush(Colors.Blue);
            //查找资源
            var solidColor = App.Current.FindResource("solidColor");
        }

  

posted on 2022-12-14 10:39  宁静致远.  阅读(52)  评论(0编辑  收藏  举报