gpt4 book ai didi

C# XAML MVVM Treeview 控件数据绑定(bind)

转载 作者:行者123 更新时间:2023-12-03 10:43:04 25 4
gpt4 key购买 nike

我无法显示项目列表。
我究竟做错了什么?

XAML( View ):

<Grid.DataContext>
<vm:MainViewModel />
</Grid.DataContext>

<Grid.Resources>
<DataTemplate x:Key="Remedy">
<TextBlock Text="{Binding Titulo}" />
</DataTemplate>

<HierarchicalDataTemplate x:Key="Laboratorio"
ItemTemplate="{StaticResource Remedy}"
ItemsSource="{Binding Items}">
<TextBlock Text="{Binding Titulo}" />
</HierarchicalDataTemplate>
<HierarchicalDataTemplate x:Key="Root"
ItemTemplate="{StaticResource Laboratorio}"
ItemsSource="{Binding Items}">
<TextBlock Text="{Binding Titulo}" />
</HierarchicalDataTemplate>

</Grid.Resources>

<TreeView x:Name="dirR"
ItemsSource="{Binding Path=Arbol}"
ItemTemplate="{StaticResource Root}">
</TreeView>

C#( View 模型):
class MainViewModel:INotifyPropertyChanged
{
private TreeItem _arbol = new TreeItem("Remedys");
public TreeItem Arbol
{
set
{
_arbol = value;
OnPropertyChanged("Arbol");
}
get { return _arbol; }
}

public MainViewModel()
{
//Populate Arbol
...
}
}

C#(模型):
public class TreeItem:INotifyPropertyChanged
{
private String _titulo;
private ObservableCollection<TreeItem> _items;
public String Titulo
{
get { return _titulo; }
set
{
_titulo = value;
OnPropertyChanged("Titulo");
}
}
public ObservableCollection<TreeItem> Items
{
get { return _items; }
set
{
_items = value;
OnPropertyChanged("Items");
}
}
public TreeItem(String __titulo)
{
Titulo = __titulo;
}

C#(主窗口 v1):
public MainWindow()
{
InitializeComponent();

}

C# (MainWindow v2) 这个版本工作正常,但我不喜欢它,因为 View 和 Viewmodel 之间存在代码依赖关系
public MainWindow()
{
InitializeComponent();

MainViewModel vm = new MainViewModel();
dirR.Items.Add(vm.Arbol);
}

最佳答案

您只能将值绑定(bind)到 ItemsSource实现IEnumerable .一般来说你必须绑定(bind)一个收藏 ItemsSource .

更改您的 MainViewModel

class MainViewModel:INotifyPropertyChanged
{
private ObservableCollection<TreeItem> _arbol =
new ObservableCollection<TreeItem>(
new List<TreeItem>
{
new TreeItem("Remedys")
} );
public ObservableCollection<TreeItem> Arbol
{
set
{
_arbol = value;
OnPropertyChanged("Arbol");
}
get { return _arbol; }
}

public MainViewModel()
{
//Populate Arbol
...
}
}

关于C# XAML MVVM Treeview 控件数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44942442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com