سؤال

This might be a duplicate question, but I'm unable to find a good answer. All the answers like Binding WinForms ListBox to object properties don't work on my WinForm. I'll explain.

I have a list of Firms that I show in a ListBox. I would like when the SelectedItem changes, that it updates a property on my model. So that I can read the Firms properties.

// the classes
public class Firm
{
    public string Name { get; set; }
    public int Id { get; set; }
    // more properties ...
}

public class MyModel : INotifyPropertyChanged
{
    private Firm _firm = new Firm();
    public Firm Firm
    {
        get { return _firm; }
        set
        {
            if (Equals(value, _firm)) return;
            _firm = value;
            OnPropertyChanged();
        }
    }
    // more properties and OnPropertyChanged() ...
}

// the form
private MyModel Model;

public void MyForm(List<Firm> firms)
{
    lstFirm.DataBindings.Add("SelectedItem", Model, "Firm",
        true, DataSourceUpdateMode.OnPropertyChanged);
    lstFirm.DisplayMember = "Name";
    lstFirm.ValueMember = "Id";
    lstFirm.DataSource = firms;
}

public void lstFirm_SelectedIndexChanged(object sender, EventArgs e)
{
    // Do something with Model.Firm
}

The problem is that Model.Firm null is. Does anybody have an idea what I need to do to make a databinding between the ListBox and the Model? I bind other stuff on my WinForm (such as TextBoxes to String properties) and those work nicely.

هل كانت مفيدة؟

المحلول 2

Ok, so after a weekend of testing, I figured it out.

I was debuging in the SelectedIndexChanged event and didn't see the change in my Model.Firm just yet. But as the SelectedItemChanged event is only internal, I couldn't use that and that's where the databinding on SelectedItem applies the values to databound items.

Now the reason why the change isn't visible yet, is because the SelectedItemChanged is only fired after the SelectedIndexChanged is executed. So internally in the ListBox control, it probably looks like

this.SelectedIndex = value;
this.SelectedItem = FindItem(value);
this.SelectedIndexChanged(/*values*/);
this.SelectedItemChanged(/*values*/); // Apply databinding changes

So it's quite normal that you don't see the changes, before the change has occured. And I didn't know this, so I was kinda stumped why the SelectedItem (who was displaying the changed value) wasn't copied over to the databound model property.

So I didn't have to change anything major to get it all working. :)

نصائح أخرى

From what I can see, your code never sets Model.Firm... Where's the constructor for MyModel? If you don't provide one, Model.Firm will stay null unless you explicitly set it. Here's an example constructor:

public MyModel(Firm firm)
{
    _firm = firm;
}

Also, Equals() doesn't do what you think it does. Instead of if (Equals(value, _firm)) return;, use this: if (value == _firm) return;

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top