开发者

WPF User Control Binding Issue?

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


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.


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜