在Code Behind中动态更改XAML样式,以便应用该样式的控件也反映了更改

时间:2012-04-27 05:23:47

标签: c# wpf styles

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

我的问题是,如果我有30个矩形,所有这些矩形我想要具有相同的样式(我不想单独更新所有这些矩形)。我想将它们全部设置(在xaml文件中)为相同的样式,然后更新样式以便按照我喜欢的方式。

假设我在每个矩形的Xaml中设置Style = "key1"。然后我希望能够稍后修改“key1”,以便所有矩形都能反映出这种变化。

我试过App.xaml

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

在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));
}

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

这可能吗?有谁知道如何做到这一点? (非常感谢一个例子)。

3 个答案:

答案 0 :(得分:12)

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

<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;

答案 1 :(得分:2)

值得一提的是,款式一旦使用就会密封,因此无法更改。这就是为什么样式应该被另一个实例替换而不是更新的原因。

答案 2 :(得分:0)

创建了一些静态助手,用法示例:

SetStyle(typeof(ContentPage), 
   (ContentPage.BackgroundColorProperty, Color.Green), 
   (ContentPage.PaddingProperty, new Thickness(20)));

Helper方法:

    public static Style CreateStyle(Type target, params (BindableProperty property, object value)[] setters)
    {
        Style style = new Style(target);
        style.ApplyToDerivedTypes = true;
        foreach (var setter in setters)
        {
            style.Setters.Add(new Setter
            {
                Property = setter.property,
                Value = setter.value
            });
        }
        return style;
    }

    public static void SetStyle(Type target, params (BindableProperty property, object value)[] setters)
    {
        Style style = new Style(target);
        style.ApplyToDerivedTypes = true;
        foreach (var setter in setters)
        {
            style.Setters.Add(new Setter
            {
                Property = setter.property,
                Value = setter.value
            });
        }
        Application.Current.Resources.Add(style);
    }