2011-09-14 23 views
1

首先,讓我說我一直在使用WPF約一個星期。我想要設置一個TextBox的樣式,以便當它被禁用時,它被清除。 This本文介紹瞭如何做到這一點,但是我對如何設置通用風格作爲資源困惑讓每一個文本框可以綁定到一個不同的屬性,而不需要重複式的每個文本框。TextBox觸發器使用樣式來清除文本

<Window.Resources> 
     <Style TargetType="{x:Type TextBox}" x:Key="style1"> 
      <Setter Property="Text" Value="{What do I really put here?}" /> 
      <Style.Triggers> 
       <Trigger Property="IsEnabled" Value="False"> 
        <Setter Property="Text" Value="{x:Null}" /> 
       </Trigger> 
      </Style.Triggers> 
     </Style> 
    </Window.Resources> 

....

<TextBox Style="{StaticResource style1}" Text="{Binding SomeProperty}"/> 

謝謝!

回答

2

您將無法使用Text屬性這樣。在具有這種風格將覆蓋觸發Text制定者(如你注意到)任何TextBox明確設置Text財產。

如果你只需要TextBox被清除,而不是它是有約束力的財產,那麼解決方法是使用一個附加屬性(或Tag)爲您綁定TextStyle文本。
實施例..

<Style TargetType="{x:Type TextBox}" x:Key="style1"> 
    <Setter Property="Text" Value="{Binding RelativeSource={RelativeSource Self}, 
              Path=Tag}"/> 
    <Style.Triggers> 
     <Trigger Property="IsEnabled" Value="False"> 
      <Setter Property="Text" Value="{x:Null}" /> 
     </Trigger> 
    </Style.Triggers> 
</Style> 

然後,TextBox可以使用此Style

<TextBox Style="{StaticResource style1}" Tag="{Binding SomeProperty}" />