TreeView和数据绑定失败

时间:2018-12-08 19:16:13

标签: c# wpf mvvm data-binding observablecollection

我正在研究MVVM模式和TreeView。

我无法将数据模型与视图绑定。这是我当前的代码:

MainWindow.xaml:

xmlns:reptile="clr-namespace:Terrario.Models.Reptile"
...
<TreeView x:Name="TrvFamily" Grid.Row="1" Grid.Column="0" ItemsSource="{Binding }">
            <TreeView.ItemTemplate>
                <HierarchicalDataTemplate DataType="{x:Type reptile:Family}" ItemsSource="{Binding Items}">
                    <TextBlock Text="{Binding Name}" />
                </HierarchicalDataTemplate>
            </TreeView.ItemTemplate>
        </TreeView>

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        LoadFamily();
    }

MainWindow.xaml.cs:

    private void LoadFamily()
    {
        FamilyVM familiesVM = new FamilyVM();
        familiesVM.Load();
        TrvFamily.DataContext = familiesVM;
    }
}

ViewModels \ FamilyVM:

class FamilyVM
{
    public ObservableCollection<Family> Families { get; set; }

    public void Load()
    {
        ObservableCollection<Family> families = new ObservableCollection<Family>();

        families.Add(new Family { ID = 1, Name = "Amphibian" });
        families.Add(new Family { ID = 2, Name = "Viperidae" });
        families.Add(new Family { ID = 3, Name = "Aranae" });

        Families = families;
    }
}

Models \ Family.cs

    class Family
{
    public int ID { get; set; }
    public string Name { get; set; }
}

TreeView仍然是白色的,就像没有数据一样。

希望您有问题;)

感谢前进

1 个答案:

答案 0 :(得分:1)

您要绑定到FamilyVM实例而不是Families。 没有Name属性,因此您一无所获。

您还应该始终在任何视图模型上实现inotifypropertychanged。 否则会导致内存泄漏。

而且您在Family上没有子代。

    <TreeView x:Name="TrvFamily" Grid.Row="1"
              ItemsSource="{Binding Families}">
        <TreeView.ItemTemplate>
            <HierarchicalDataTemplate DataType="{x:Type local:Family}" ItemsSource="{Binding SomeCollectionYouDoNotHaveYet}">
                <TextBlock Text="{Binding Name}" />
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>

通常将inotifypropertychanged的内容放在继承视图模型的基类中。

class FamilyVM : INotifyPropertyChanged
{
    private ObservableCollection<Family> families = new ObservableCollection<Family>();

    public ObservableCollection<Family> Families
    {
        get { return families; }
        set { families = value; NotifyPropertyChanged(); }
    }

    public void Load()
    {
        ObservableCollection<Family> families = new ObservableCollection<Family>();
        families.Add(new Family { ID = 1, Name = "Amphibian" });
        families.Add(new Family { ID = 2, Name = "Viperidae" });
        families.Add(new Family { ID = 3, Name = "Aranae" });
        Families = families;
    }
    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}