Binding a WPF Style Trigger to a custom dependency property

11,869

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>
Share:
11,869
WPFNewbie
Author by

WPFNewbie

Updated on July 20, 2022

Comments

  • WPFNewbie
    WPFNewbie almost 2 years

    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.

  • Balázs Szántó
    Balázs Szántó almost 9 years
    Why? The simple Trigger should support dependency properties, shouldn't it?