【问题标题】:Why does my application enter break mode when I bind to a collection?为什么我的应用程序在绑定到集合时会进入中断模式?
【发布时间】:2019-06-15 01:23:39
【问题描述】:

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

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


【解决方案1】:

UserCard 控件位于ItemsControlItemTemplate 中:

<ItemsControl ItemsSource="{Binding UserViewModel.Users}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <controls:UserCard/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

【讨论】:

  • 哦!那么ItemsControl 需要指定ItemTemplate 吗?
  • 是的,如果您想使用 UserCard 显示源集合中的每个项目。
  • 这一切都适用吗?假设我想显示一个TextBlock 控件。我是否必须明确使用ItemsControl.ItemTemplate,因为我现在的看法是我需要使用ItemsControl.ItemTemplate 来明确指定我要呈现的数据类型
  • 您可以定义ItemTemplate DisplayMemberPath 属性设置为要在ItemsControl 中显示的数据对象的属性名称.当您使用 ItemsSource 属性时,您不能将项目直接添加到 ItemsControl
  • 哦,好吧,我想知道为什么不能直接从ItemSourceItemsControl 添加项目,不过我还是要去MSDN 上看看!谢谢!我会尽快接受答案。
猜你喜欢
  • 2010-11-26
  • 1970-01-01
  • 2016-01-22
  • 2019-06-23
  • 1970-01-01
  • 2019-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多