wpf 如何从触发器绑定到另一个控件的属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2520483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:37:01  来源:igfitidea点击:

How do I bind to another control's property from a trigger?

wpfxamltriggersstyles

提问by rrhartjr

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.

在我的特定情况下,我想绑定到 TextBox 的 IsReadOnly 属性来设置 Button 的 Content 属性?它们都是同一个 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.

我已经尝试使用 DataTrigger 与 TextBox 的 ElementName 绑定和使用 TextBox 名称作为 SourceName 的触发器。

Any thoughts?

有什么想法吗?

回答by itowlson

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 本身的 Triggers 集合只能包含事件触发器。考虑到这一点,DataTrigger 工作正常。但是,有一个问题:来自 Trigger Setter 的值不会覆盖本地 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>

回答by Mark

Have you tried this:

你有没有试过这个:

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

??

??