views:

145

answers:

1

Hi.

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>
+1  A: 

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>
Kishore Kumar
pls see the updated answer
Kishore Kumar
Kishore - thanks, the last update worked.
Matteo Caprari