如何在树视图中设置不同的样式控制级别1和2?

时间:2012-12-12 00:09:14

标签: c# wpf treeview styles hierarchicaldatatemplate

我现在正在使用TreeView。正如您所看到的,CurrentMediumObjectivesChildrenObjective是同一个名为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,我会感到困惑。 提前谢谢。

1 个答案:

答案 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
{
}

结果: enter image description here