2010-02-01 37 views
1

我要瘋了!我錯過了什麼以及它爲什麼沒有造型:無法調整我的WPF控件

<Style x:Key="textBoxStyle" TargetType="{x:Type TextBox}"> 
       <Style.Triggers> 
        <Trigger Property="IsFocused" Value="True"> 
         <Setter Property="Background" Value="Red" /> 
        </Trigger> 
       </Style.Triggers> 
      </Style> 

    <TextBox Width="100" Style="{StaticResource textBoxStyle}" Height="20" Background="Yellow" ></TextBox> 

上面的代碼不會做任何事情。它不會突出顯示TextBox控件!

回答

4

這是因爲本地值覆蓋樣式值。 (直接在元素上設置的屬性具有很高的優先級)。您正在TextBox上直接設置Background,所以WPF正在進行,「嗯,他通常希望textBoxStyle背景在聚焦時爲紅色,但對於這個特定的TextBox,他說他特別希望背景是黃色,所以它是黃色。「

因此,解決方法是把黃色的背景是風格的一部分:

<Style x:Key="textBoxStyle" TargetType="{x:Type TextBox}"> 
    <Setter Property="Background" Value="Yellow" /> 
    <Style.Triggers> 
    <Trigger Property="IsFocused" Value="True"> 
     <Setter Property="Background" Value="Red" /> 
    </Trigger> 
    </Style.Triggers> 
</Style> 

,並從文本框刪除:

<TextBox Width="100" Style="{StaticResource textBoxStyle}" Height="20" /> 
+0

i ndeed,我匆忙,壓倒一切的風格價值似乎是實際問題 – arconaut 2010-02-01 20:33:37

+0

其實風格是在Window.Resources – azamsharp 2010-02-01 20:39:29

+0

定義的工作!但現在的問題是,豐富的風格控制。我應該將代碼中的所有內容都移動到樣式中。 – azamsharp 2010-02-01 20:44:07

0

定義您Style之前的TextBox或使用DynamicResource代替StaticResource

+0

Actuall它是在Window.Resources中的TextBox之前定義的 – azamsharp 2010-02-01 20:40:26

+0

從靜態更改爲動態沒有幫助! – azamsharp 2010-02-01 20:46:40

相關問題