我无法显示项目列表。 我做错了什么?
XAML(查看):
<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#(ViewModel):
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#(MainWindow v1):
public MainWindow()
{
InitializeComponent();
}
C#(MainWindow v2)此版本正常但我不喜欢它,因为View和Viewmodel之间存在代码依赖
public MainWindow()
{
InitializeComponent();
MainViewModel vm = new MainViewModel();
dirR.Items.Add(vm.Arbol);
}
答案 0 :(得分:0)
在MainWindow代码中设置DataContext:
来自XAML:
<Window.DataContext>
<vm:MainWindowViewModel/>
</Window.DataContext>
来自代码:
public MainWindow()
{
InitializeComponent();
DataContext = new MainViewModel();
}
答案 1 :(得分:0)
您只能将值绑定到实现ItemsSource
的{{1}}。一般来说,您必须将集合绑定到IEnumerable
。
将ItemsSource
更改为
MainViewModel