修改数据绑定 WPF TreeView 上的单个 TreeViewItem,而不修改数据源
我有一个 MVVM WPF 应用程序,其中 TreeView 数据绑定到视图模型类。它本质上是一个文件浏览器。我想向层次结构添加“添加新文件夹”的功能。为了实现所需的功能,我要做的只是将文本块切换为数据模板中的可编辑文本框。这就是我的数据模板的样子:
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<StackPanel Name="tv_itempanel"
Orientation="Horizontal"
Margin="2">
<Image Source="{Binding Icon}" Margin="4"/>
<TextBlock Name="treeitem_tblock" Margin="4" Text="{Binding Name}"/>
<TextBox Width="200" Visibility="Collapsed" Name="treeitem_tbox"/>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
问题是我无法修改单个 TreeViewItem,因为树视图是数据绑定的。有什么想法吗?谢谢
I've got a MVVM WPF app with the TreeView databound to a viewmodel class. It is essentially a file explorer. I want to add the ability to "Add a new folder" to the hierarchy. To achieve the desired functionality what I am trying to do is simply switch the Textblock out for an editable TextBox in my datatemplate. This is what my datatemplate looks like:
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<StackPanel Name="tv_itempanel"
Orientation="Horizontal"
Margin="2">
<Image Source="{Binding Icon}" Margin="4"/>
<TextBlock Name="treeitem_tblock" Margin="4" Text="{Binding Name}"/>
<TextBox Width="200" Visibility="Collapsed" Name="treeitem_tbox"/>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
The problem is that I cannot modify an individual TreeViewItem since the treeview is databound. Any ideas? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将
bool IsEditable
属性添加到您的 VM 对象,并将TextBox
的可见性绑定到 is(使用转换器将布尔值转换为Visibility
代码>枚举)。这样您就不需要直接操作TreeViewItem
,只需将数据对象标记为可编辑,它就会自然地流向您的视图。Add a
bool IsEditable
property to your VM objects, and bind the visibility of theTextBox
to is (using a converter to transform the boolean value to aVisibility
enum). That way you don't need to manipulate theTreeViewItem
directly, simply mark the data object as editable, and it will flow naturally to your view.