我现在正在使用TreeView。正如您所看到的,CurrentMediumObjectives
和ChildrenObjective
是同一个名为Objective
的对象类型。
此类有一个名为Level
的属性,其中ChildrenObjective
设置为1,ChildrenObjective
设置为2.
我想根据DataTemplate
设置不同的Level
。
<TreeView ItemsSource="{Binding CurrentMediumObjectives}"
Margin="0,40,0,0">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding ChildrenObjective}">
<TextBlock FontWeight="Bold">
<Run Text="Objective " />
<Run Text="{Binding Level}" />
</TextBlock>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
如果我应该使用DataTemplateSelector或DataTrigger,我会感到困惑。 提前谢谢。
答案 0 :(得分:2)
也许您可以使用Trigger
来显示每个模板。这样的事情,可能:
<TreeView ItemsSource="{Binding CurrentMediumObjectives}" Margin="0,40,0,0">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding ChildrenObjective}">
<Grid>
<!--Data template for level 1-->
<TextBlock x:Name="level1" FontWeight="Bold">
<Run Text="Objective " />
<Run Text="{Binding Level}" />
</TextBlock>
<!--Data template for level 2-->
<TextBlock x:Name="level2" FontWeight="Bold" Foreground="Red">
<Run Text="Objective " />
<Run Text="{Binding Level}" />
</TextBlock>
</Grid>
<HierarchicalDataTemplate.Triggers>
<DataTrigger Binding="{Binding Level}" Value="1">
<Setter TargetName="level1" Property="Visibility" Value="Visible" />
<Setter TargetName="level2" Property="Visibility" Value="Collapsed" />
</DataTrigger>
<DataTrigger Binding="{Binding Level}" Value="2">
<Setter TargetName="level2" Property="Visibility" Value="Visible" />
<Setter TargetName="level1" Property="Visibility" Value="Collapsed" />
</DataTrigger>
</HierarchicalDataTemplate.Triggers>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
模特(猜猜)
public class Objective
{
public int Level { get; set; }
}
public class CurrentMediumObjectives : Objective
{
public ObservableCollection<ChildrenObjective> ChildrenObjective { get; set; }
}
public class ChildrenObjective : Objective
{
}
结果: