在选择TreeViewItem时,我在更改用于TreeViewItem的DataTemplate时遇到一些问题。理想情况下,我希望每个项目都包含TextBlock
,然后在选中时,它应包含TextBox
。
这是我到目前为止(我使用this question作为起点):
<Window>
<Window.Resources>
<HierarchicalDataTemplate x:Key="normal"
ItemsSource="{Binding Path=Children}">
<TextBlock Text="{Binding Path=Text}" />
</HierarchicalDataTemplate>
<HierarchicalDataTemplate x:Key="selected"
ItemsSource="{Binding Path=Children}">
<TextBox Text="{Binding Path=Text}" />
</HierarchicalDataTemplate>
<Style TargetType="{x:Type TreeViewItem}" x:Key="ContainerStyle">
<Setter Property="ItemTemplate" Value="{StaticResource normal}" />
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="ItemTemplate" Value="{StaticResource selected}" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Resource>
<Grid>
<TreeView ItemSource="{Binding Body}" ItemContainerStyle="{StaticResource ContainerStyle}" />
</Grid>
</Window>
结果是树中只有一个节点,节点的文本是对象的类型名称。听起来像绑定到节点的类型不是模板所期望的类型,因此它使用默认的ToString()
绑定而不是我指定的Text
属性。
我在代码隐藏文件中设置了Window的DataContext。我知道我的数据绑定是正确的,因为如果我为TreeView设置了一个HierarchicalDataTemplate
,数据就会正确显示。
我认为我的问题是我需要在ItemTemplate
样式中设置TreeViewItem
以外的属性 - 我使用正确的属性,还是应该设置其他内容?
答案 0 :(得分:3)
它实际上是您需要的HeaderTemplate - 这就是控制节点本身风格的原因。就这样有一个完整的样本,这对我有用:
<Window x:Class="Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<HierarchicalDataTemplate x:Key="normal"
ItemsSource="{Binding Path=Children}">
<TextBlock Text="{Binding Path=Text}" />
</HierarchicalDataTemplate>
<HierarchicalDataTemplate x:Key="selected"
ItemsSource="{Binding Path=Children}">
<TextBox Text="{Binding Path=Text}" />
</HierarchicalDataTemplate>
<Style TargetType="{x:Type TreeViewItem}"
x:Key="ContainerStyle">
<Setter Property="HeaderTemplate"
Value="{StaticResource normal}" />
<Style.Triggers>
<Trigger Property="IsSelected"
Value="True">
<Setter Property="HeaderTemplate"
Value="{StaticResource selected}" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<TreeView x:Name="_Tree" ItemContainerStyle="{StaticResource ContainerStyle}"/>
</Grid>
</Window>
..后面有一些测试代码:
Imports System.Collections.ObjectModel
Class Window1
Private Sub Window1_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
Dim Root As New Node
Root.Text = "Root"
Dim Child As New Node
Child.Text = "Child"
Root.Children.Add(Child)
Dim Nodes As New Collection(Of Node)
Nodes.Add(Root)
_tree.itemssource = Nodes
End Sub
End Class
Public Class Node
Private _Text As String
Public Property Text() As String
Get
Return _Text
End Get
Set(ByVal Value As String)
_Text = Value
End Set
End Property
Private _Children As New Collection(Of Node)
Public Property Children() As Collection(of node)
Get
Return _Children
End Get
Set(ByVal Value As Collection(of node))
_Children = Value
End Set
End Property
End Class