views:

1893

answers:

2

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.

+8  A: 

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.

bennage
Hmm, after rereading your question, I don't think that I really answered it.
bennage
This is basically the right answer. Set up your binding/styles as normal and add a trigger to DataContext is x:Null to switch to a different set of styles/bindings.
Bryan Anderson
This was actually what I was looking for. I was so caught up in the RelativeSource, FindAncestor, Self whatever syntax so I forgot that all I wanted to know was how to check if a property was null.
Robert Höglund
A: 
<Border>
    <Border.Style>
        <Style TargetType="Border">
            <Setter Property="Background"
                    Value="Orange" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding}"
                             Value="{x:Null}">

If Value is not equal to say, what can I do ???

                    <Setter Property="Background"
                            Value="Yellow" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Border.Style>
</Border>