绑定到集合后,为什么我的应用程序进入中断模式?

时间:2019-01-21 16:01:07

标签: c# .net wpf mvvm data-binding

我当前正在尝试绑定ItemSource中的ItemsControl,但是由于某种原因,它引发了一个问题,即应用程序已进入中断模式,我不知道是什么原因,我真的想了解为什么它进入中断模式,我尝试调试,但并没有真正使我走得很远。

目标是创建一个自定义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));
    }
}

1 个答案:

答案 0 :(得分:1)

UserCard控件进入ItemTemplate的{​​{1}}中:

ItemsControl
相关问题