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?
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>
精彩评论