【问题标题】:WPF multiple control property simultaneous changesWPF多个控件属性同时更改
【发布时间】:2015-06-08 14:29:05
【问题描述】:

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

我可以在堆栈面板中设置TextElement.Foreground,设置文本框的前景色等(参见下面的代码)。但是,这不会改变 Button、ListBox 等的前景色。

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

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

【问题讨论】:

  • 如何设置WindowForeground
  • 我不认为改变Window Foreground会改变TextBox前景,例如...
  • @MikeEason 根据您的建议,结果仍然与上面的代码相同。抱歉,不起作用。

标签: wpf xaml


【解决方案1】:

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

【讨论】:

    【解决方案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>
    

    【讨论】:

      【解决方案3】:

      前两个答案是正确的。经过更多的研究,我还想提一下这可以通过tree traversal来完成。

      我找到的一些参考资料:This SO question and answersMSDN article "Trees in WPF."

      【讨论】:

      • @DanPuzey 我完全同意!只是想提一下这是一个选项,即使对于这个问题的上下文来说不是最好的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-17
      • 2012-07-02
      • 1970-01-01
      • 1970-01-01
      • 2012-02-15
      • 2018-05-20
      • 2018-12-23
      相关资源
      最近更新 更多