2015-12-08 87 views
0

我试图用MVVM模式编写一个简单的WPF应用程序,但显示列表元素不起作用我很确定绑定有什么问题,因为它第一次与它绑定C#WPF MVVM不能显示列表的元素

<Window.Resources> 
     <local:ViewModel x:Key="test"/> 
    </Window.Resources> 
    <Grid> 
     <ListView Name="lstPersons" ItemsSource="{Binding test.peopleList}" > 
      <ListView.View> 
        <GridView.Columns> 
         <GridViewColumn Header="name" DisplayMemberBinding="{Binding name}" /> 
         <GridViewColumn Header="surname" DisplayMemberBinding="{Binding surname}" /> 

视图模型片段:

public class ViewModel 
{ 
    private personModel.Root peopleDB = new personModel.Root(); 
    public ViewModel() 
    { } 

    public List<personModel.Person> peopleList 
    { 
     get { return peopleDB.people; } 
    } 

Model类片段:

public class Root 
    { 
     public List<Person> people; 

     public Root() 
     { 
      people = new List<Person>(); 
      people.Add(new Person("aa", "aa", 1, new Adress("bb", "cc"))); 
      people.Add(new Person("bb", "bb", 1, new Adress("bb", "cc"))); 
      people.Add(new Person("cc", "cc", 1, new Adress("bb", "cc"))); 
     } 
    } 


    public class Person 
    { 
     public string name { get; set; } 
     public string surname { get; set; } 
     public int age { get; set; } 
     public Adress address { get; set; } 

试了几件事情有约束力,但他们没有工作:/

+0

我想的问题之一是你需要设置DataContext。 '<视图模型:视图模型/>'。 – Borophyll

+0

您需要将绑定的来源从默认(当前'.DataContext')更改为您的.Resources中找到的版本。 – Rachel

回答

1

这里的问题听起来像你的DataContext没有设置。

有多种方式可以做到这一点。作为escull638 said,你可以手动的窗口中使用任何XAML

<Window.DataContext> 
    <local:ViewModel> 
</Window.DataContext> 

或代码隐藏

this.DataContext = new ViewModel(); 

硬编码的DataContext并改变你现在结合了.DataContext设置正确

<ListView ItemsSource="{Binding peopleList}"> 

但请记住,硬编码.DataContext这样通常只在您的应用程序的最高级别使用,并且它不应该是使用WPF时常见的东西。 WPF中的控件非常“不看”,而绑定系统用于将它们的数据传递给它们,所以通过对硬件进行编码DataContext意味着您不能将控件与任何其他数据对象一起使用,哪种类型会破坏最大的优势之一使用WPF。

另一种解决办法是改变你的绑定的Source属性,因此它指向<Window.Resources>

<ListView ItemsSource="{Binding Source={StaticResource test}, Path=peopleList}"> 

我更喜欢这种方式,因为很明显定义的静态对象只盯着ListView的XAML所绑定到一个静态的源代码,并且当你试图将一个动态源代码传递给Control并发现DataContext没有设置为你所期望的时,它会保存所有类型的头痛。

作为一个侧面说明,如果你无法理解什么DataContext是或它是如何工作的,我倾向于初学者链接到this answer of mine这解释比较详细:)

1

设置的DataContext到视图模型中加入给你的XAML文件:

<Window.DataContext> 
    <local:ViewModel> 
</Window.DataContext> 

然后,当你需要绑定你可以使用的东西:

<ListView Name="lstPersons" ItemsSource="{Binding peopleList}" > 
+0

附注 - 我讨厌这种设置'DataContext'的方式..这意味着你的视图绑定到它自己的数据副本,并且它不能被绑定或从别处传入。它确实有效,如果你开始的话,这很好。只是不要使用它太多:) – Rachel

+0

另一种替代方法是在视图的xaml.cs构造函数中设置DataContext。 DataContext = new ExampleViewModel(); – escull638