views:

801

answers:

1

Hi

I have the following XAML:

<Grid x:Name="root">
   <Grid.RowDefinitions>
    <RowDefinition Height="*"/>
    <RowDefinition Height="Auto"/>
 </Grid.RowDefinitions>
<Grid.Resources>
  <DataTemplate DataType="{x:Type ViewModels:TemplateViewModel}">
    <ContentControl Content="{Binding}" Grid.Row="0" x:Name="ct">
      <ContentControl.ContentTemplate>
        <DataTemplate>
          <TextBlock Text="Loaded" />
         </DataTemplate>
      </ContentControl.ContentTemplate>
    </ContentControl>
    <DataTemplate.Triggers>
      <DataTrigger Binding="{Binding DataContext.State, 
        RelativeSource={RelativeSource AncestorType={x:Type Window}}}" Value="2">
        <Setter Property="ContentTemplate" TargetName="ct">
          <Setter.Value>
            <DataTemplate>
              <TextBlock Text="Loading, please wait"  Foreground="Red"/>
            </DataTemplate>
          </Setter.Value>
        </Setter>
      </DataTrigger>
    </DataTemplate.Triggers>
  </DataTemplate>
</Grid.Resources>
<ContentControl Content="{Binding MainContent}" />

That XAML is inside a Window element. I'm binding the Window to a ViewModel object with two properties, State and MainContent:

public class ViewModel : INotifyPropertyChanged {
   public int State {...} // this can be only 1 or 2, for simplicity
   public TemplateViewModel MainContent { ... } 
}

I raise the PropertyChanged event from the property setters accordingly.

Now, with a button I load a file from disk, parse it and create an object to assign to the MainContent property. Before parsing I set the State property to 2 (loading) and after assigning I reset the property to 1 (loaded).

The first time I parse the file, the trigger in the data template doesn't work (notice the trigger is bound to the State property of the Data Context of the parent Window, that is, the ViewModel object). But the second time, it does!

Can somebody point where's the error?

I'm afraid I cannot post the code here, but could share it if you have an answer and give me an email..

+1  A: 

Your DataTemplate is applied to type TemplateViewModel instead of ViewModel. Ergo, it won't apply to anything until the MainContent property is set.

HTH, Kent

Kent Boogaart