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


Wpf Problem Overview

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?

Wpf Solutions

Solution 1 - Wpf

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 -->
    <Style TargetType="Button">
      <Setter Property="Content" Value="You may write!!!" />  <!-- Here is the 'normal' content -->
        <!-- 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 -->

Solution 2 - Wpf

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



All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrrhartjrView Question on Stackoverflow
Solution 1 - WpfitowlsonView Answer on Stackoverflow
Solution 2 - WpfMarkView Answer on Stackoverflow