我有以下 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}" />
该 XAML 位于 Window 元素内。我将 Window 绑定到具有两个属性 State 和 MainContent 的 ViewModel 对象:
public class ViewModel : INotifyPropertyChanged {
public int State {...} // this can be only 1 or 2, for simplicity
public TemplateViewModel MainContent { ... }
}
我相应地从属性设置器中引发 PropertyChanged 事件。
现在,我使用一个按钮从磁盘加载文件,对其进行解析并创建一个对象以分配给 MainContent 属性。在解析之前,我将 State 属性设置为 2(正在加载),在分配之后我将属性重置为 1(已加载)。
第一次解析文件,数据模板中的触发器不起作用(注意触发器绑定到父Window的Data Context的State属性,即ViewModel对象)。但第二次,确实如此!
有人可以指出错误在哪里吗?
恐怕我无法在此处发布代码,但如果您有答案并给我发电子邮件,可以分享它..