2

我现在正在使用 TreeView。如您所见CurrentMediumObjectives, 和 ChildrenObjective是相同的对象类型,称为Objective.

此类有一个名为 的属性Level,其中 inChildrenObjective设置为 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 感到困惑。提前致谢。

4

1 回答 1

2

也许您可以只使用 aTrigger来显示每个模板。

像这样的东西,也许:

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

结果: 在此处输入图像描述

于 2012-12-12T00:19:38.293 回答