Binding a WPF Style Trigger to a custom dependency property

删除回忆录丶 提交于 2020-01-02 01:47:08

问题


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


来源:https://stackoverflow.com/questions/11758836/binding-a-wpf-style-trigger-to-a-custom-dependency-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!