Question

I have this:

public MyView: UserControl
{
  public IList<Person> PersonList { get; set; } 

  public MyView()
  {
   //code
  }

  public void Display(MyData myData)
  {
    DataContext=myData;
  }
  //code
}

The XAML for this includes a ComboBox :

ItemsSource="{Binding RelativeSource={RelativeSource Self}, Path=PersonList}"

For some reason this does not work and the combo box does not get populated ( however, If I use the code-behind and I say comboBox.ItemsSource = PersonList then the combo box does got populated ).

Any ideas ?

Regards, MadSeb

Was it helpful?

Solution

Your property is set to private, and are you sure that you are setting the DataContext.

* EDIT *

Based on the change you made above, you're setting your datacontext incorrectly. Your "PersonList" is anIList<> on your MyView class, but you're setting your data context to something else.

Try adding items to PersonList within MyView and setting this.DataContext = this; Also, as suggested, switch your IList<> to an ObservableCollection<>.

I would also highly suggest reading up on the Model View ViewModel (MVVM) approach. It will help out a lot. Josh Smith has a lot of good articles about the MVVM approach (and has written a good book about it too).

Here's a link to his blog. His book is linked there, as well.

OTHER TIPS

I suspect it's because you're not firing any property-changed events. If you don't notify your UI when the property's value is first set, the binding won't update. Look into the INotifyPropertyChanged interface and implement it in your class.

Similarly, if your IList property isn't an ObservableCollection or doesn't implement INotifyCollectionChanged, then when you add items to the list the databound UI won't reflect this.

I believe your binding statement is the problem.
"{Binding RelativeSource={RelativeSource Self}, Path=PersonList}" is looking for a "PersonList" on the combobox itself.

Are you seeing any binding errors in the output window?

Ideally you'd want to bind to a property in your DataContext (MyData)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top