【发布时间】:2019-06-15 01:23:39
【问题描述】:
我目前正在尝试绑定我的ItemsControl 的ItemSource,但由于某种原因,它抛出了一个问题,说应用程序已进入中断模式,我不知道原因是什么,我真的很想了解为什么它正在进入中断模式,我尝试调试,但它并没有真正让我走得很远。
目标是创建一个自定义UserControl,然后通过单击按钮将它们添加到ObservableCollection。所以当按钮被点击时创建一个新的,不幸的是我没有走那么远,因为这开始发生了。
所以我的问题是,为什么会抛出这个问题,是不是它不喜欢绑定?
<ItemsControl ItemsSource="{Binding UserViewModel.Users}">
<controls:UserCard/>
</ItemsControl>
我已经像这样设置了 DataContext
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new BaseViewModel();
}
}
对于 BaseViewModel,它看起来像这样
public class BaseViewModel : ObservableObject
{
public UserViewModel UserViewModel { get; set; } = new UserViewModel();
}
UserViewModel 看起来像这样
public class UserViewModel : ObservableObject
{
public ObservableCollection<User> Users { get; set; } = new ObservableCollection<User>();
public UserViewModel()
{
}
}
像这样的 ObservableObject
public class ObservableObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
【问题讨论】:
-
好点!下次我提出问题时,我会确保澄清这一点!
标签: c# .net wpf mvvm data-binding