在代码隐藏中动态更改 XAML 样式,以便应用该样式的控件也反映更改 [英] Changing XAML style dynamically in Code Behind so that controls applying that style also reflect the change

查看:27
本文介绍了在代码隐藏中动态更改 XAML 样式,以便应用该样式的控件也反映更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够从 WPF 窗口中的 .cs 文件设置样式属性(和值).

I want to be able to set style properties (and values) from the .cs file in my WPF window.

我的问题是,如果我有 30 个矩形,我希望所有矩形都具有相同的样式(并且我不想单独更新所有矩形).我想让它们(在 xaml 文件中)都设置为相同的样式,然后更新样式以使其看起来像我想要的那样.

My problem is if I have 30 rectangles, all of which I want to have the same style (and I don't want to update all of them individually). I'd like to have them all set (in the xaml file) to the same style, and then update the style to look the way I'd like.

假设我在 Xaml 中为每个矩形设置了 Style = "key1".然后我希望能够稍后修改key1",以便所有矩形都会反映该更改.

Say I set the Style = "key1" in the Xaml for each rectangle. Then I want to be able to modify "key1" later so all the rectangles will reflect that change.

我在 App.xaml

<Application.Resources>
    <Style x:Key="key1" TargetType="Rectangle">
        <Setter Property="Fill" Value="Red"/>
    </Style>
</Application.Resources>

在 MainwWindows.xaml 中

In MainwWindows.xaml

<StackPanel>
    <Rectangle Style="{StaticResource key1}" Height="200" Width="200" x:Name="rect1"/>
    <Button Click="Button_Click" Content="Click"/>
</StackPanel>

在代码后面

private void Button_Click(object sender, RoutedEventArgs e)
{
    Style style = Application.Current.Resources["key1"] as Style;
    style.Setters.Add(new Setter(Rectangle.VisibilityProperty, Visibility.Collapsed));
}

这会更新样式,但不会更新矩形.

This updates the style but do not update the rectangles.

这可能吗?有谁知道如何做到这一点?(一个例子将不胜感激).

Is this possible? Does anyone know how to do this? (An example would be greatly appreciated).

推荐答案

您需要使用 DynamicResource 以便它可以在运行时更改.您还需要用新样式替换样式,而不是尝试修改现有样式.这有效:

You need to use DynamicResource so that it can be changed at run-time. You also need to replace the style with a new one, not try to modify the existing one. This works:

<StackPanel>
    <Rectangle Style="{DynamicResource key1}" Height="200" Width="200" x:Name="rect1"/>
    <Button Click="Button_Click" Content="Click"/>
</StackPanel>

Style style = new Style {TargetType = typeof(Rectangle)};
style.Setters.Add(new Setter(Shape.FillProperty, Brushes.Red));
style.Setters.Add(new Setter(UIElement.VisibilityProperty, Visibility.Collapsed));

Application.Current.Resources["key1"] = style;

这篇关于在代码隐藏中动态更改 XAML 样式,以便应用该样式的控件也反映更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆