当并非所有控件都是相同类型时,如何更改XAML窗口中多个控件的前台属性?
我可以在堆栈面板中设置TextElement.Foreground,以设置TextBoxes的前景色等(参见下面的代码)。但是,这不会改变按钮、ListBoxes等的前景色。
如何设置窗口中所有元素的前景色,而不为每个单独的元素或元素类设置它?
<Window x:Class="XAMLViewTests.AnimationsWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="AnimationsWindow" Height="300" Width="300">
<StackPanel TextElement.Foreground="Blue">
<ToolBarTray>
<ToolBar>
<TextBlock>Test Tray 1</TextBlock>
</ToolBar>
<ToolBar>
<TextBlock>Test Tray 2</TextBlock>
</ToolBar>
<ToolBar>
<Button>Test Tray 3</Button>
</ToolBar>
</ToolBarTray>
<TextBlock>Test TextBlock</TextBlock>
<Button>Test Button</Button>
<ListBox>ListBox 1
<ListBoxItem>Item 1</ListBoxItem>
<ListBoxItem>Item 2</ListBoxItem>
</ListBox>
</StackPanel>
</Window>发布于 2015-06-08 14:36:20
我认为,如果您希望TextBlock / TextBox / Button等的所有实例都受到影响,那么您需要为每个控件分别设置一次样式。
<Window.Resources>
<Style TargetType="TextBlock">
<Setter Property="Foreground" Value="White"/>
</Style>
<Style TargetType="TextBox">
<Setter Property="Foreground" Value="White"/>
</Style>
<Style TargetType="Button">
<Setter Property="Foreground" Value="White"/>
</Style>
<Window.Resources>发布于 2015-06-08 14:47:22
关于James的回答:您可以使用WPF继承样式的能力,以及Foreground是基类Control类的属性这一事实,以减少setter的复制:
<Style TargetType="Control">
<Setter Property="Foreground" Value="Red" />
</Style>
<Style BasedOn="{StaticResource {x:Type Control}}" TargetType="Button">
<!-- optionally add button-specific stuff here... -->
</Style>
<Style BasedOn="{StaticResource {x:Type Control}}" TargetType="TextBox">
<!-- optionally add textbox-specific stuff here... -->
</Style>
<Style BasedOn="{StaticResource {x:Type Control}}" TargetType="ComboBox">
<!-- optionally add ComboBox-specific stuff here... -->
</Style>发布于 2015-06-08 16:04:29
前两个答案是正确的。经过更多的研究,我还想提到这可以通过树遍历来完成。
我发现的一些参考资料:这个问题和答案和MSDN文章“WPF中的树”。
https://stackoverflow.com/questions/30711891
复制相似问题