代码之家  ›  专栏  ›  技术社区  ›  jostyposty

具有未知级别的WPF树视图中叶节点的自己模板

  •  1
  • jostyposty  · 技术社区  · 15 年前

    我正在尝试向WPF中TreeView的叶节点添加复选框。如果层次结构中有固定数量的级别,并且对每个级别使用层次结构数据模板,我知道如何做到这一点。但如果我想要这个怎么办:
    -节点1
    --节点1a(带复选框的叶节点)
    --节点1b
    ---节点1bi(带复选框的叶节点)
    -节点2
    --节点2a(带有复选框的叶节点)

    我将代码文件中的DataContext设置为DataTable。只有一张桌子,和它本身有关系。

    DataContext = ds.MyDataTable;
    

    XAML:

    <UserControl x:Class="JostyWpfControls.UserControl1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        Height="240" Width="312">
        <UserControl.Resources>
            <HierarchicalDataTemplate x:Key="myTemplate" 
                ItemsSource="{Binding myDatasetRelation}">
                <CheckBox IsChecked="{Binding IsChosen}">
                    <TextBlock Text="{Binding Description}"/>
                </CheckBox>
            </HierarchicalDataTemplate>
        </UserControl.Resources>
        <Grid>
            <TreeView x:Name="treeView" 
                ItemsSource="{Binding}" 
                ItemTemplate="{StaticResource myTemplate}">
            </TreeView>
        </Grid>
    </UserControl>
    

    这是有效的,但为所有节点提供了一个chechbox。我只希望叶节点有一个复选框。

    1 回复  |  直到 15 年前
        1
  •  4
  •   Drew Noakes    15 年前

    您可以使用数据模板中的触发器来确定复选框是否应可见:

    <HierarchicalDataTemplate x:Key="myTemplate" 
                              ItemsSource="{Binding myDatasetRelation}">
      <StackPanel>
        <CheckBox x:Name="CheckBox" IsChecked="{Binding IsChosen}" 
                  Content="{Binding Description}" />
        <TextBlock x:Name="LeafLabel" Text="{Binding Description}"
                   Visibility="Collapsed" />
      </StackPanel>
      <HierarchicalDataTemplate.Triggers>
        <DataTrigger Binding="{Binding myDatasetRelation.Count}" Value="0">
          <Setter TargetName="CheckBox" Property="Visibility" Value="Collapsed" />
          <Setter TargetName="LeafLabel" Property="Visibility" Value="Visible" />
        </DataTrigger>
      </HierarchicalDataTemplate.Triggers>
    </HierarchicalDataTemplate>
    

    我不确定值是否绑定到via myDatasetRelation 有一个 Count 属性,但如果不是,则可以使用 Length 或者找到其他方法来确定它是否为空(可能使用 IValueConverter 如果没有更简单的方法。

    推荐文章