jos*_*sty 2 wpf treeview hierarchicaldatatemplate
我正在尝试将复选框添加到 WPF 中 TreeView 中的叶节点。如果我们在层次结构中有固定数量的级别并为每个级别使用 HierarchicalDataTemplate,我知道如何执行此操作。但是当我想要这个时该怎么做:
-Node 1
-- Node 1a (leaf node with checkbox)
-- Node 1b
--- Node 1bI (leaf node with checkbox)
-Node 2
-- Node 2a (leaf node with checkbox)
我将代码文件中的 DataContext 设置为 DataTable。只有一张桌子,与它本身有关。
DataContext = ds.MyDataTable;
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
这是有效的,但给了我一个所有节点的检查箱。我只希望叶节点有一个复选框。
您可以在数据模板中使用触发器来确定复选框是否应该可见:
<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>
Run Code Online (Sandbox Code Playgroud)
我不确定绑定到 via 的值是否myDatasetRelation具有Count属性,但如果没有,那么您可以使用Length或找到其他方法来确定它是否为空(也许使用IValueConverterif 没有更简单的方法可用。
| 归档时间: |
|
| 查看次数: |
2143 次 |
| 最近记录: |