我希望能够在我的WPF窗口的.cs文件中设置样式属性(以及值)。 我的问题是,如果我有30个矩形,它们都想要拥有相同的样式(而我不想逐个更新它们),我希望将它们全部设置(在xaml文件中)为相同的样式,然后更新样式以呈现我所需的外观。
假设我在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));
}
这会更新样式但不会更新矩形。
这可行吗?有人知道如何做到吗?(提供示例将会非常感激)。
Update()
或Refresh()
方法。试一下,也许这可以帮助解决问题。 - stukselbax