Display a default DataTemplate in a ContentControl when its content is null or empty?
Simple, you have to bind the content property in the style. Styles won't overwrite a value on a control if there's a binding present, even if the value evaluates to Null. Try this.
<ContentControl> <ContentControl.Style> <Style TargetType="ContentControl"> <Setter Property="Content" Value="{Binding HurfView.EditedPart}" /> <Style.Triggers> <DataTrigger Binding="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=Content}" Value="{x:Null}"> <Setter Property="ContentControl.Template"> <Setter.Value> <ControlTemplate> <Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> <TextBlock>EMPTY!</TextBlock> </Grid> </ControlTemplate> </Setter.Value> </Setter> </DataTrigger> </Style.Triggers> </Style> </ContentControl.Style></ContentControl>
Since I stumbled upon this question and had the same problem today, I wanted to contribute another way how I solved the problem. Since I did not like to add another style trigger I used the property TargetNullValue
which seems to be a bit more readable than the accepted solution (which works nevertheless):
<ContentControl> <ContentControl.Content> <Binding Path="ContentViewModel"> <Binding.TargetNullValue> <Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> <TextBlock>EMPTY!</TextBlock> </Grid> </Binding.TargetNullValue> </Binding> </ContentControl.Content> </ContentControl>
You could return DBNull.Value as the FallbackValue of the Binding for the Content of the ContentControl, and create a DataTemplate for DBNull :
<DataTemplate DataType="{x:Type system:DBNull}"> <!-- The default template --></DataTemplate>...<ContentControl Content="{Binding HurfView.EditedPart, FallbackValue={x:Static system:DBNull.Value}}" />