views:

375

answers:

1

I have a custom dependency property that I would like to use as a data trigger. Here is the code behind:

public static readonly DependencyProperty BioinsulatorScannedProperty =
    DependencyProperty.Register(
        "BioinsulatorScanned", 
        typeof(bool), 
        typeof(DisposablesDisplay), 
        new FrameworkPropertyMetadata(false));

    public bool BioinsulatorScanned
    {
        get
        {
            return (bool)GetValue(BioinsulatorScannedProperty);
        }
        set
        {
            SetValue(BioinsulatorScannedProperty, value);
        }
    }

I have created a style and control template. My goal is to change the color of some text when the dependency prop is set to true...

<Style x:Key="TreatEye" TargetType="Label">
        <Setter Property="Foreground" Value="#d1d1d1" />
        <Setter Property="FontWeight" Value="Bold" />
        <Setter Property="FontSize" Value="30" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Label">
                    <Canvas>                            
                        <TextBlock x:Name="bioinsulatorText" 
                                   Canvas.Left="21" Canvas.Top="33" 
                                   Text="Bioinsulator" />
                        <TextBlock Canvas.Left="21" Canvas.Top="70" 
                                   Text="KXL Kit" />
                    </Canvas>

                    <ControlTemplate.Triggers>
                        <DataTrigger Binding="{Binding BioinsulatorScanned}"
                                     Value="True">
                            <Setter TargetName="bioinsulatorText" 
                                    Property="Foreground" Value="Black" />
                        </DataTrigger>
                    </ControlTemplate.Triggers>

                </ControlTemplate>
            </Setter.Value>
        </Setter>            
    </Style>

Despite successfully setting the dependency prop to true programmatically, This trigger condition never fires. This is a real pain to debug!

Thanks in advance.

+2  A: 

It looks like your dependency property is defined inside a DisposableDisplay object that you created. In order for the binding specified to work, an instance of that DisposableDisplay object must be set as the DataContext of the control (label in this case) or any of its ancestors.

Aviad P.
This works perfectly. As a WPF novice, I've found data binding to be one of the most troublesome topics. In which cases does DataContext not need to be set?
Tim
`DataContext` is set by default when you use data templates. And data templates are used by default in items controls (list boxes, list views, data grids, etc.) Also, you may explicitly set the datacontext on any element to better facilitate binding. It's one of the most important concepts in WPF.
Aviad P.