2015-06-08 47 views
1

如何更改XAML窗口中多個控件的前景屬性,當不是所有控件都是相同類型?WPF多個控件屬性同時發生變化

我可以在一個堆棧面板中設置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> 
+0

如何設置'Window'的'Foreground'? –

+0

我不認爲改變窗口前景將改變TextBox的前景,例如... –

+0

@MikeEason與你的建議,結果仍然是上面的代碼相同。對不起,不起作用。 –

回答

2

我想你需要的款式要單獨影響控制操作 - 但只是一次爲每個 - 假設你要的TextBlock /文本框/按鈕等的所有實例受到影響。

<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

而且詹姆斯的回答:你可以使用WPF的繼承方式的能力,而事實上,Foreground是基Control類的屬性,以減少二傳手的重複:

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

前面兩個答案是正確的。經過更多的研究,我也想提到這可以通過樹遍歷來完成。

一些參考文獻,我發現:This SO question and answersMSDN article "Trees in WPF."

+1

雖然通過樹遍歷在代碼中執行此操作非常笨拙,並且將XAML作爲您的表示層,因爲您必須定義代碼中的樣式。 –

+0

@DanPuzey我同意所有的計數!只是想提及這是一個選擇,即使這個問題的背景不是最好的。 –

相關問題