2010-03-26 78 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

相关问题