奇怪的行为 WPF TreeView ItemContainerStyle 和 ItemTemplate
我刚刚注意到 WPF 的 TreeView 的一些奇怪行为。我添加了 ItemContainerStyle 来绑定到 ViewModel 的“IsSelected”,并添加了 ItemsTemplated 来自定义数据显示。但现在用户无法再更改所选节点。出于测试目的,我使用 ListView 和 Expander 创建了类似的 UI。此版本的工作方式除外。 TreeView 失败的任何提示?
<TreeView ItemsSource="{Binding ElementName=frame, Path=list}">
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}" >
<Setter Property="IsSelected" Value="{Binding Mode=TwoWay, Path=IsSelected}"/>
</Style>
</TreeView.ItemContainerStyle>
<TreeView.ItemTemplate>
<HierarchicalDataTemplate>
<TreeViewItem Header="{Binding}">
<TextBlock Text="{Binding Path= Item.SomeData}"/>
</TreeViewItem>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
编辑:我的数据不是分层的。我只想在显示列表时获得“折叠”功能。 Item.SomeData 不是列表。数据的显示是根据需要的。只有鼠标选择失败!
I just noticed some strange behaviour of WPF's TreeView. I added both ItemContainerStyle to bind to "IsSelected" of my ViewModel and an ItemsTemplated for custom display of my data. But now the user cannot change the selected node anymore. For testing purposes I created a similar UI using ListView and Expander. This version works as excepted. Any tips why TreeView does fail?
<TreeView ItemsSource="{Binding ElementName=frame, Path=list}">
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}" >
<Setter Property="IsSelected" Value="{Binding Mode=TwoWay, Path=IsSelected}"/>
</Style>
</TreeView.ItemContainerStyle>
<TreeView.ItemTemplate>
<HierarchicalDataTemplate>
<TreeViewItem Header="{Binding}">
<TextBlock Text="{Binding Path= Item.SomeData}"/>
</TreeViewItem>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
EDIT: My data are not hierachical. I just want to get the "collapse" feature on displaying a list. Item.SomeData is not a list. Display of data is as desired. Only selection by mouse fails!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
TreeView 的工作方式有所不同。 HierarchicalDataTemplate 内的项目是 TreeViewItems,您在 HierarchicalDataTemplate 内指定的任何控件都将用作其标头。因此,基本上您指定 TreeView 中的项目是 TreeViewItems,并以 TreeViewItems 作为标题!相反,请尝试以下操作:
编辑:我无法重现生成您想要绑定的属性的数据源,因此我自己编写了一些简单的代码来显示它的工作原理。希望您能够根据您的需求进行调整:
TreeViews work differently. The Items inside a HierarchicalDataTemplate are TreeViewItems and any control you specify inside the HierarchicalDataTemplate will function as its Header. So, basically you are specifying that the Items in your TreeView are TreeViewItems with TreeViewItems as their headers! Instead try this:
EDIT: I could not reproduce a DataSource that produces the properties you want to bind to, so I wrote some simple code of my own that shows how it all works. Hopefully you will be able to adapt it to your needs: