在代码后台动态更改XAML样式,以便应用该样式的控件也反映出更改。

11
我希望能够在我的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));
}

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

这可行吗?有人知道如何做到吗?(提供示例将会非常感激)。


我认为你需要在UI元素(整个窗口或矩形区域)上调用Update()Refresh()方法。试一下,也许这可以帮助解决问题。 - stukselbax
3个回答

16

您需要使用 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;

我能只在XAML端完成它吗? - dellos

4
值得一提的是,样式表在使用后就会被锁定,因此无法更改。这就是为什么应该用另一个实例替换样式表而不是更新它的原因。

1
创建了一些静态帮助程序,用法示例:
SetStyle(typeof(ContentPage), 
   (ContentPage.BackgroundColorProperty, Color.Green), 
   (ContentPage.PaddingProperty, new Thickness(20)));

辅助方法:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接