c# - WPF 绑定(bind) View 模型

标签 c# wpf mvvm

所以我目前正在尝试使用 MVVM 学习 WPF,并且我正在在线学习一些教程。现在我有一个简单的项目,我尝试自己做,但不知何故 ListBox 保持为空。我认为它不会绑定(bind)到 ViewModel。我在这里想念什么?

View 模型:

public class PersonViewModel
{
    ObservableCollection<Person> Personen { get; set; } = new ObservableCollection<Person>();

    public PersonViewModel()
    {
        Personen.Add(new Person { Vorname = "My", Nachname = "Name", Email = "my@name.com" });
        Personen.Add(new Person { Vorname = "Max", Nachname = "Mustermann", Email = "max@mustermann.de" });
        Personen.Add(new Person { Vorname = "John", Nachname = "Doe", Email = "john@doe.com" });
        Personen.Add(new Person { Vorname = "Jane", Nachname = "Doe", Email = "jane@doe.com" });
    }
}

}

另外,我正在像这样设置我的 DataContext:
public PersonenView()
{
    InitializeComponent();
    this.DataContext = new ViewModel.PersonViewModel();
}

最佳答案

您只需要在 ViewModel 中为 ObservableCollection Personen 提供一个公共(public)访问器。

您还应该将属性设为只读(或从其 setter 触发属性更改通知):

public ObservableCollection<Person> Personen { get; }
    = new ObservableCollection<Person>();

关于c# - WPF 绑定(bind) View 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56322447/

相关文章:

c# - 如何在asp中每天运行cron作业。网络核心应用?

c# - 多级 tabcontrol - 我们使用哪个集合来绑定(bind) mvvm

c# - 在带有 Prism mvvm View 模型的xamarin形式的xaml中包括xaml。无法解析INavigationService

c# - 暂停/阻止复选框控件的动画

wpf - 为什么应该为 WPF、SL 和 WP7 使用 UI 模式框架?

c# - Xamarin.Forms 无法安装包

c# - ASP.NET 图表控件和字符编码问题

C#如何将嵌套类的构造函数只暴露给父类的成员?

控件模板中的 WPF 嵌套绑定(bind)

c# - 使用查询字符串打开 html 文件