如何为treeViewItems使用dataTemplate
本文关键字:使用 dataTemplate treeViewItems | 更新日期: 2023-09-27 18:04:31
下面的代码抛出一个异常:
<TreeView
ItemsSource="{Binding TreeRootInstance}"
x:Name="Htree"
ItemTemplate="CellTemplate"
SelectedItemChanged="HTree_OnSelectedItemChanged"
KeyDown="HTree_KeyDown">
<TreeView.Resources>
<DataTemplate x:Key="CellTemplate">
<Border>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<ToggleButton x:Name="Expander"
HorizontalAlignment="Right"
Focusable="False"
Grid.Column="1"
IsChecked="{Binding Path=IsExpanded, RelativeSource={RelativeSource AncestorType={x:Type vw:TreeViewItem}}}"
ClickMode="Press"/>
<TextBlock
Text="{Binding Name}"
Grid.Column="0" />
</Grid>
</Border>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Path=HasItems, RelativeSource={RelativeSource AncestorType={x:Type TreeViewItem}}}" Value="False">
<Setter TargetName="Expander" Property="Visibility" Value="Hidden"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
<Style TargetType="{x:Type TreeViewItem}" x:Key="aa">
<Setter Property="IsTabStop" Value="True"/>
<Setter Property="TabIndex" Value="0"/>
<Setter Property="IsExpanded" Value="{Binding Path=IsExpanded,Mode=TwoWay}"/>
<Setter Property="ItemsSource" Value="{Binding Children}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TreeViewItem}">
<StackPanel>
<Border Name="Bd">
</Border>
<ItemsPresenter x:Name="ItemsHost" />
</StackPanel>
<ControlTemplate.Triggers>
<Trigger Property="IsExpanded" Value="false">
<Setter TargetName="ItemsHost"
Property="Visibility"
Value="Collapsed"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="{x:Type TreeView}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TreeView}">
<Border BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="ItemContainerStyle" Value="{StaticResource aa}" />
</Style>
</TreeView.Resources>
</TreeView>
(我省略了一些代码,但主要的层次结构仍然存在…)异常是在ItemsControl.ItemTemplate上的一个xaml解析异常。
你能告诉我如何使这段代码工作吗?
谢谢,李
您不能使用普通字符串作为资源定位符,您需要使用StaticResource标记扩展,即ItemTempate="{StaticResource CellTemplate}"
ItemTemplate行应该是:
ItemTemplate="{StaticResource CellTemplate}"