10
votes

I have found numerous similar threads here, but none that seem to address my specific issue.

I need to highlight the background of a textbox under certain conditions. I have created a Highlight property and tried using a trigger in a style to set it but it doesn't actually ever highlight the text.

Here is my Style, simplified:

<Style x:Key="TextBoxStyle" BasedOn="{StaticResource CommonStyles}">
    <Style.Triggers>
        <Trigger Property="Elements:DataElement.Highlight" Value="True">
            <Setter Property="Control.Background"
                    Value="{DynamicResource EntryBoxHighlightBackground}"/>
        </Trigger>
    </Style.Triggers>
</Style>

Elements is defined as:

xmlns:Elements="clr-namespace:MDTCommon.Controls.Forms.Elements">

Then I have the section where the style is applied:

<!-- Applies above style to all TextBoxes -->
<Style TargetType="TextBox" BasedOn="{StaticResource TextBoxContentHolder}" >
    <Setter Property="Validation.ErrorTemplate" Value="{x:Null}" />
    <!-- Overrides the default Error Style -->
</Style>

In the code behind of the DataElement class is the following:

public static readonly DependencyProperty HighlightProperty = 
    DependencyProperty.Register("Highlight", typeof(bool), typeof(DataElement));

public bool Highlight
{
    get { return (bool)base.GetValue(HighlightProperty); }
    set { base.SetValue(HighlightProperty, value); }
}

A DataElement ultimately derived from UserControl and it contains a reference to TextBox object as well as othe objects.

In the CustomForm class that houses all of the DataElement objects I have the following to set the color.

Resources["EntryBoxHighlightBackground"] = Brushes.Yellow;

So, the first issue is that setting the Highlight property for the DataElement doesn't cause the textbox background to draw in yellow.

The other issue is that I realize that I am applying this style to all textboxes and I could have textboxes in other areas that are not actually contained within a DataElement, which may cause a binding issue.

1
Try to add a setter 'background' to your style - niao
I left out a lot of the Style to keep it simple and focus on the areas where I think the problem might be. - WPFNewbie
Just to be sure: shouldn't you also specify an assembly for "Elements" in XAML? Does the output window shows any errors? - niao

1 Answers

7
votes

Try converting your trigger to a DataTrigger, and add a binding that will look directly at the DataElement control, like so:

<DataTrigger Binding="{Binding Path=Highlight, RelativeSource={RelativeSource AncestorType={x:Type Elements:DataElement}}}" Value="True">
    <Setter Property="Control.Background" Value="{DynamicResource EntryBoxHighlightBackground}"/>
</DataTrigger>