1
votes

I have looked at the similar questions to this on here, but could not find one that fit my error (that worked). My code is:

public MainWindow()
    {
        InitializeComponent();
    }

    public List<item> loadedCategory = new List<item>();

    private void Open_Click(object sender, RoutedEventArgs e)
    {
        OpenFileDialog openFileDialog = new OpenFileDialog();
        if (openFileDialog.ShowDialog() == true)
        {
            List<item> loadedCategory = loaders.category_loader(openFileDialog.FileName);
        }

        left_panel_lower_list.ItemsSource = loadedCategory;
    }

the item object is just a DTO that holds 4 properties. loaders.category_loader returns a list of items. The error is marked at the end of the ItemSource assignment line. I have tried moving the assignment line to most other places in the code, and it never runs.
What am I doing wrong?

3

3 Answers

1
votes

I would do as:

private ObservableCollection<item> loadedCategory = new ObservableCollection<item>();

public MainWindow()
{
    InitializeComponent();
    left_panel_lower_list.ItemsSource = loadedCategory;
}

private void Open_Click(object sender, RoutedEventArgs e)
{
    OpenFileDialog openFileDialog = new OpenFileDialog();
    if (openFileDialog.ShowDialog() == true)
    {
        foreach(var item in loaders.category_loader(openFileDialog.FileName)
        {
            loadedCategory.Add(item);
        }
    }        
}

...as long as based on your code. You should prepare a view model and use binding anyway.

0
votes

Your code above has a scoping error as you are redefining a local variable with the same name as the field in your class. Effectively, you are getting the data and then ignoring it by adding the field which appears to be empty thus the problem I think.

0
votes

You should understand the meaning of error message carefully.

Error: Items collection must be empty before using ItemsSource in Listbox

This means your ListBox must not contain any item before you assign something to ItemsSource.

Steps to reproduce this problem :

  1. Use a combo-box and add some items to it in XAML code directly.
  2. Then in code-behind set it's itemssource property.
  3. You will get this exception.

How to avoid this error :

Use either Items Collection or ItemsSource, but not both.