Goran
Goran

Reputation: 6518

Setting background of content control

<UserControl .....>
  <DataTemplate DataType="{x:Type vm:AViewModel}">
    <vw:AView />
  </DataTemplate>

  <DataTemplate DataType="{x:Type vm:BViewModel}">
    <vw:BView />
  </DataTemplate>

  <ContentControl x:Name="chartScreen" Content="{Binding Screen}" Background="Yellow" />
</UserControl>

As you can see from above code, ContentControl is setting its content through binding to ViewModel's Screen property. Screen property will return an instance of AViewModel or BViewModel, depending on some condition. The problem is, when UserControl is loaded on screen, Screen property is null, so there is no content set yet. At this point, I would like to set some background for the ContentControl, but I cannot find a way how to do this? Background="Yellow" does nothing...

Any ideas how to set the background of ContentControl? This backgound should be applied always, even when content is displaying AView or Biew, or null.

Upvotes: 7

Views: 6634

Answers (3)

juFo
juFo

Reputation: 18577

try something like this in WPF:

 <ContentControl>
      <ContentControl.Style>
        <Style TargetType="ContentControl">
          <Style.Triggers>
            <DataTrigger Binding="{Binding Content}" Value="{x:Null}">
              <Setter Property="Content">
                <Setter.Value>
                  <Rectangle Width="100" Height="100" Fill="Blue" />
                </Setter.Value>
              </Setter>
            </DataTrigger>
          </Style.Triggers>
        </Style>
      </ContentControl.Style>
</ContentControl>

Upvotes: 0

Viv
Viv

Reputation: 17388

Just wrap your ContentControl in a Border

<Border Background="Yellow">
  <ContentControl x:Name="chartScreen"
                  Content="{Binding Screen}" />
</Border>

If all you have in your UserControl is your ContentControl, just set the Background on the UserControl itself. That would remove the extra Border as well.

Upvotes: 8

eran otzap
eran otzap

Reputation: 12533

try something like this :

 <ContentControl x:Name="chartScreen" Content="{Binding Screen}" Background="Yellow">
       <ContentControl.Triggers>    
           <Trigger Property="Content" Value="{x:Null}">
               <Trigger.Value>
                   <Border Background="Yellow"/>
               </Trigger.Value> 
           </Trigger>  
       </ContentControl.Triggers>    
 </ContentControl>

Upvotes: 1

Related Questions