views:

2095

answers:

1

Hi,

I have a listbox which is databound to a collection of objects. I want to modify the way the items are displayed to show the user which one of these objects is the START object in my program.

I tried to do this the following way, but the listbox does not automatically update. Invalidating the control also didn't work.

The only way I can find is to completely remove the databindings and add it back again. but in my case that is not desirable.

Is there another way?

class Person : INotifyPropertyChanged
{
 public event PropertyChangedEventHandler PropertyChanged;

 private string _name;
 public string Name
 {
  get
  {
   if (PersonManager.Instance.StartPerson == this)
    return _name + " (Start)";      
   return _name;
  }
  set
  {
   _name = value;
   if (PropertyChanged != null)
    PropertyChanged(this, new PropertyChangedEventArgs("Name"));
  }
 }

 public Person(string name)
 {
  Name = name;
 }
}

This is the class wich manages the list and the item that is the start

class PersonManager
{
 public BindingList<Person> persons { get; set; }
 public Person StartPerson { get; set; }

 private static PersonManager _instance;
 public static PersonManager Instance
 {
  get
  {
   if (_instance == null)
   {
    _instance = new PersonManager();
   }
   return _instance;
  }
 }

 private PersonManager()
 {
  persons = new BindingList<Person>();
 }
}

In the form I use the following code

 private void button1_Click(object sender, EventArgs e)
 {
  PersonManager.Instance.StartPerson = (Person)listBox1.SelectedItem;
 }
A: 
Reed Copsey
Thanks a lot for the speedy response, that worked like a charm!
sjors miltenburg
just to be curious, how would you have solved this problem if you would have coded something like this from scratch?
sjors miltenburg
A potentially cleaner way might be to have something like a Name + DisplayName property. Alternatively, if you had a property that determined whether a person was the "Start" person, setting it would raise the event. There are a lot of options - it really depends on how it's going to be used.
Reed Copsey
In my actual code i have 2 properties (Name + NameInclStart). I now have a working example, but unfortunately my actual code does not work (with the exact same logic) :S. Anyway the reason I set it up like this was that the items themselves where responsible for displaying themselves correctly.
sjors miltenburg
Just make sure that, when you change either property (esp. NameInclStart), you're going to have a PropertyChanged event fire.I recommend adding a third, get only property (DisplayName), and calling NotifyChanged(..., "DisplayName") when you set Name OR NameInclStart. That will "fix" it.
Reed Copsey