2010-03-26 53 views
42

在我的特殊情況下,我想綁定到TextBox的IsReadOnly屬性來設置Button的Content屬性?它們都是同一個StackPanel的一部分。如何從觸發器綁定到其他控件的屬性?

我試着用DataTrigger綁定到TextBox的ElementName和使用TextBox名稱作爲SourceName的觸發器。

有什麼想法?

回答

63

您需要將觸發器指定爲樣式的一部分 - Button本身上的Triggers集合只能包含事件觸發器。考慮到這一點,DataTrigger可以正常工作。但是,有一個摺痕:觸發器設置器的值不會覆蓋本地Content屬性。所以你必須在樣式中設置默認的內容。以下是它的外觀:

<Button> <!-- Note no content set directly on button --> 
    <Button.Style> 
    <Style TargetType="Button"> 
     <Setter Property="Content" Value="You may write!!!" /> <!-- Here is the 'normal' content --> 
     <Style.Triggers> 
     <!-- Here is how we bind to another control's property --> 
     <DataTrigger Binding="{Binding IsReadOnly, ElementName=textBox}" Value="True"> 
      <Setter Property="Content" Value="NO NO NO" /> <!-- Here is the 'override' content --> 
     </DataTrigger> 
     </Style.Triggers> 
    </Style> 
    </Button.Style> 
</Button> 
+1

啊哈!我知道有一個屬性優先級,但是我沒有想到直接覆蓋Trigger動作。 我使用DP作爲綁定源,並以與嘗試使用ElementName相同的行爲結束,所以問題實際上是屬性的優先級。 感謝您的清理! – rrhartjr 2010-03-26 01:58:32

+0

這是非常好的。正是我所需要的,我幾乎要編碼一個轉換器。但是這更好。 – user1841243 2013-10-22 12:42:41

+0

>但是,有一個摺痕:觸發器設置器的值不會覆蓋本地Content屬性。 這很重要! 我第一次看到這個答案時就錯過了。 – SteveP 2017-11-13 10:32:53

5

你有沒有嘗試過這樣的:

<StackPanel x:Name="LayoutRoot"> 
    <Button Width="75" Content="{Binding IsReadOnly, ElementName=textBox, Mode=Default}" /> 
    <TextBox x:Name="textBox" VerticalAlignment="Top" Text="TextBox" /> 
</StackPanel> 

+0

他可能希望他的按鈕通過\ * grin \ *來說比True或False更有意義的內容。當然,你可以通過插入一個轉換器來實現,但觸發器確實感覺更習慣...... – itowlson 2010-03-26 01:17:13

+0

Mark,我編輯了你的代碼,去除了一些無關的位,我覺得很難看出你的建議的核心。希望這是好的 - 如果你覺得我扭曲了你的意圖,那麼請回滾。 – itowlson 2010-03-26 01:23:40

+0

這很好,謝謝你,我只是把它掀起來很快,可能應該清理它:) – Mark 2010-03-26 01:53:08

相關問題