如何从触发器绑定到另一个控件的属性? [英] How do I bind to another control's property from a trigger?

查看:110
本文介绍了如何从触发器绑定到另一个控件的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的特定情况下,我想绑定到TextBox的IsReadOnly属性以设置Button的Content属性吗?它们都是同一个StackPanel的一部分。



有什么想法吗?

解决方案

您需要指定作为样式的一部分的触发器-Button本身的Triggers集合只能包含事件触发器。考虑到这一点,DataTrigger可以正常工作。但是,这是有问题的:触发器设置器中的值不会覆盖本地内容属性。因此,您还必须在样式中设置默认的内容。外观如下:

 < Button> <!-注意没有在按钮上直接设置任何内容-> 
< Button.Style>
< Style TargetType = Button>
< Setter Property = Content Value =您可以写!!! /> <!-这是正常内容->
< Style.Triggers>
<!-这是我们如何绑定到另一个控件的属性->
< DataTrigger Binding = {Binding IsReadOnly,ElementName = textBox} Value = True>
< Setter Property = Content Value = NO NO NO /> <!-这是替代内容->
< / DataTrigger>
< /Style.Triggers>
< / Style>
< /Button.Style>
< / Button>


In my particular case, I want to bind to the IsReadOnly property of a TextBox to set the Content property of a Button? They are both part of the same StackPanel.

I've tried doing it with a DataTrigger with a Binding to the ElementName of the TextBox and a Trigger using the TextBox name as the SourceName.

Any thoughts?

解决方案

You need to specify the trigger as part of a style -- the Triggers collection on the Button itself can only contain event triggers. With that in mind, a DataTrigger works fine. However, there is a wrinkle: the value from the Trigger Setter won't overwrite a local Content property. So you have to set the default Content in the Style as well. Here's how it looks:

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

这篇关于如何从触发器绑定到另一个控件的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆