Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I trigger a style change if DataContext is null or not using WPF

I have a page with several controls. The controls are bound to display values which they get from the page's DataContext. What I would like to do is display another look of the page should the DataContext be null. In some cases the controls of the page should display differently if "their" property is set or not.

Is is possible to create a binding to see if the DataContext is set?

What I did as a workaround was to add a IsDataContextSet property to the page and the specify a binding like:

Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Page}}, Path=IsDataContextSet}" Value="false"

This works as I expect but I have a feeling that their is more elegant way to do this. Or at least or more WPFish way.

like image 881
Robert Höglund Avatar asked Nov 13 '08 08:11

Robert Höglund


1 Answers

Given the scenario you describe, I would set the properties with a style and a data trigger. The data trigger would use the default binding which is the data context.

An example might look like this:

<Border>
    <Border.Style>
        <Style TargetType="Border">
            <Setter Property="Background"
                    Value="Orange" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding}"
                             Value="{x:Null}">
                    <Setter Property="Background"
                            Value="Yellow" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Border.Style>
</Border>

The border will be orange unless the data context is null, in which case the background is yellow.

like image 103
Christopher Bennage Avatar answered Sep 27 '22 20:09

Christopher Bennage