简体   繁体   中英

WPF changing Background of a label within UserControl using DependencyProperty

I have a very simple UserControl as shown below. I'm trying to get the background of the Label element to change whenever a property in the control changes, but it's not working: when I change the Selected property on the control instance, the label's background color does not change.

Thanks!

Code behind:

    public static readonly DependencyProperty SelectedProperty =
            DependencyProperty.Register("Selected",
            typeof(bool),
            typeof(UICatcherContactlistItem),
            new FrameworkPropertyMetadata((bool)false));

    public bool Selected
    {
        get { return (bool)GetValue(SelectedProperty); }
        set { SetValue(SelectedProperty, value); }
    }

Xaml:

<UserControl x:Class="UICatcherContactlistItem" [....]> 
    <Label Name="name" Foreground="#888888">
        <Style TargetType="{x:Type Label}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Selected}" Value="True">
                    <Setter Property="Background" Value="Red"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding Selected}" Value="False">
                    <Setter Property="Background" Value="Blue"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Label>    
</UserControl>

just give the UserControl name to execute this code, here iam using test. If you are using Dependency property on the usercontrol you can access the property by either ElementName property or you have to set the Datacontext for the element like name.DataContext=this..

<Label Name="name" Foreground="#888888" Content="text" Height="100" HorizontalAlignment="Stretch" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" >
        <Label.Style>

        <Style TargetType="{x:Type Label}">
            <!--<Setter Property="Background" Value="Yellow"/>-->
            <Style.Triggers>
                <DataTrigger Binding="{Binding Selected,ElementName=test}" Value="True">
                    <Setter Property="Background" Value="Red"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding Selected,ElementName=test}" Value="False">
                    <Setter Property="Background" Value="Blue"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
        </Label.Style>
    </Label>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM