WPF多控制属性同时发生变化

时间:2015-06-08 14:29:05

标签: wpf xaml

当不是所有控件都是同一类型时,如何在XAML窗口中更改多个控件的前景属性?

我可以在stackpanel中设置TextElement.Foreground,设置TextBoxes的前景色等(参见下面的代码)。但是,这不会改变按钮,列表框等的前景色。

如何为窗口中的所有元素设置前景色,而不为每个元素或元素类设置它?

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

3 个答案:

答案 0 :(得分:3)

继James的回答:你可以使用WPF继承样式的能力,以及Foreground是基类Control类的属性,以减少setter的重复:< / p>

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

答案 1 :(得分:2)

我认为你需要为你想要单独控制的控件设置样式 - 但每个只需一次 - 假设你想要影响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>

答案 2 :(得分:0)

前两个答案是正确的。经过更多的研究,我还想提到这可以通过树遍历来实现。

我发现的一些参考文献:This SO question and answersMSDN article "Trees in WPF."