使用代码树型视图的更新绑定? (XAML / WPF)
-
13-09-2019 - |
题
我有一个TreeView
其ItemsSource
被设定为一个模型I有。 3级深是一个对象,其状态可以改变和,而不是写的每一个阶段(非常漫长的业务)视图和视图模型我想刚刚更新此使用的代码。
所以基本上我有一次我的模型更新触发的事件,我赶上然后找到该位数据相关的TreeViewItem
。我现在的问题是我对如何以更新它的绑定,以反映新的价值不知道!
谁能帮助?
我知道这是不是最好的做法,但我真的不想浪费时间编写代码巨量只更新一两件事。
由于 克里斯
解决方案
这个例子的工作原理,虽然它是只有两个(未3)级深。它示出了具有父件A,B,和C,与编号为儿童(A.1,B.1,等等)一个简单的2级分层树形视图。当点击了重命名B.1按钮时,它重命名B.1到“西尔维亚”。
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
namespace UpdateVanillaBindingValue
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
private DataClass _data;
public Window1()
{
InitializeComponent();
var data = CreateData();
DataContext = _data = data;
}
private DataClass CreateData()
{
return new DataClass
{
Parents=new List<Parent>
{
new Parent{Name="A",Children=new List<Child>{new Child{Name="A.0"},new Child{Name="A.1"}}},
new Parent{Name="B",Children=new List<Child>{new Child{Name="B.0"},new Child{Name="B.1"},new Child{Name="B.2"}}},
new Parent{Name="C",Children=new List<Child>{new Child{Name="C.0"},new Child{Name="C.1"}}}
}
};
}
private void Rename_Click(object sender, RoutedEventArgs e)
{
var parentB = _data.Parents[1];
var parentBItem = TheTree.ItemContainerGenerator.ContainerFromItem(parentB) as TreeViewItem;
parentB.Children[1].Name = "Sylvia";
var parentBItemsSource = parentBItem.ItemsSource;
parentBItem.ItemsSource = null;
parentBItem.ItemsSource = parentBItemsSource;
}
}
public class DataClass
{
public List<Parent> Parents { get; set; }
}
public class Parent
{
public string Name { get; set; }
public List<Child> Children { get; set; }
}
public class Child
{
public string Name { get; set; }
}
}
<Window x:Class="UpdateVanillaBindingValue.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">
<Grid>
<Grid.Resources>
<DataTemplate x:Key="ChildTemplate">
<TextBlock Margin="50,0,0,0" Text="{Binding Name}" />
</DataTemplate>
<HierarchicalDataTemplate x:Key="ParentTemplate" ItemsSource="{Binding Children}" ItemTemplate="{StaticResource ChildTemplate}">
<TextBlock Text="{Binding Name}" />
</HierarchicalDataTemplate>
</Grid.Resources>
<TreeView x:Name="TheTree" ItemsSource="{Binding Parents}" ItemTemplate="{StaticResource ParentTemplate}" />
<Button VerticalAlignment="Bottom" HorizontalAlignment="Center" Content="Rename B.1" Click="Rename_Click" />
</Grid>
</Window>
这是一个入侵,但它的每一个它的ItemsSource属性变化时间重新评估的DataTemplate。
在理想情况下,你会在你的模型对象类执行INotifyPropertyChanged这个树型视图结合了,并让它火PropertyChanged事件时价值变化。事实上,因为它没有你要小心,你是不是引起内存泄漏:的查找内存泄漏WPF应用。
其他提示
你确定它不会是更容易实现对相关类INotifyPropertyChanged的?
听起来像是你可能需要采取看看UpdateSource
和UpdateTarget
方法。
虽然我不能完全肯定,这时候,你实际上已经绑定的TreeView的ItemSource
的分层数据结构的工作,但它是在那里我会开始调查。
不隶属于 StackOverflow