Mark Denom
Mark Denom

Reputation: 1057

Why does my application enter break mode when I bind to a collection?

I am currently trying to bind the ItemSource of my ItemsControl but for some reason it's throwing an issue saying that the application has entered break mode and I have no idea what the cause is, I really want to understand why it's entering breakmode, I tried debugging but it didn't really get me very far.

The goal was to create a custom UserControl and then being able to add them to a ObservableCollectionwith a button click. So creating a new one when the button has been clicked, unfortunatly I didn't get that far because this started happening.

So my question is, Why is it throwing that issue, is it something where it doesnt like the binding?

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

And I've setup the DataContext like so

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = new BaseViewModel();
    }
}

And for the BaseViewModel, it looks like this

public class BaseViewModel : ObservableObject
{
    public UserViewModel UserViewModel { get; set; } = new UserViewModel();
}

And the UserViewModel looks like this

public class UserViewModel : ObservableObject
{
    public ObservableCollection<User> Users { get; set; } = new ObservableCollection<User>();

    public UserViewModel()
    {

    }
}

With an ObservableObject like so

public class ObservableObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

Upvotes: 0

Views: 106

Answers (1)

mm8
mm8

Reputation: 169300

The UserCard control goes in the ItemTemplate of the ItemsControl:

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

Upvotes: 1

Related Questions