views:

396

answers:

1

When its text is empty, I am attempting to set the background of a custom control to a visual brush using a trigger in the ControlTemplate. The following shows the relevant code:

<ControlTemplate.Triggers>
  <Trigger Property="Text" Value="">
    <Setter TargetName="MyBorder" Property="Background">
      <Setter.Value>
        <VisualBrush Opacity="0.4" Stretch="None" TileMode="None">
          <VisualBrush.Visual>
            <TextBlock Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=BackgroundText}" />
          </VisualBrush.Visual>
        </VisualBrush>
      </Setter.Value>
    </Setter>
  </Trigger>
</ControlTemplate.Triggers>

When the text is empty, however, the visual brush is not applied. However, if I create the visual brush in code and expose it as a dependency property, the following code does work:

<ControlTemplate.Triggers>
  <Trigger Property="Text" Value="">
    <Setter TargetName="MyBorder" Property="Background" Value="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=BackgroundBrush}" />
    </Setter>
  </Trigger>
</ControlTemplate.Triggers>

I would rather define the brush in XAML, though. Why does the second binding work correctly but not the first?

A: 

Are you trying to create a watermark TextBox? If so, I created mine by adding a TextBlock to the custom control, and then referenced that in the Trigger definitions. When the TextBox does not have the focus, and there is no text in the control, the Watermark (TextBlock) will be visible. Once the TexBox has the focus, the Watermark will be hidden. The text of the Watermark would then be bound to your BackgroundText property.

<ControlTemplate.Triggers>
    <MultiTrigger>
        <MultiTrigger.Conditions>
            <Condition Property="IsFocused" Value="false"/>
            <Condition Property="Text" Value="{x:Null}"/>
        </MultiTrigger.Conditions>
        <Setter TargetName="Watermark" Property="Visibility" Value="Visible"/>
    </MultiTrigger>
    <MultiTrigger>
        <MultiTrigger.Conditions>
            <Condition Property="IsFocused" Value="false"/>
            <Condition Property="Text" Value=""/>
        </MultiTrigger.Conditions>
        <Setter TargetName="Watermark" Property="Visibility" Value="Visible"/>
    </MultiTrigger>
</ControlTemplate.Triggers>
Brent
Thanks for the answer, Brent. Yes, this is what I am trying to accomplish, and I have seen a similar method to yours that works. However, the answer I am really trying to find is why the behavior of the binding changes between the two scenarios, not how to accomplish this specific task. Sorry if that wasn't clear.
Tarsier