How to bind an ItemsSource to a private property

12,068

Solution 1

DataBinding in WPF works only with public properties.

MSDN:

The properties you use as binding source properties for a binding must be public properties of your class. Explicitly defined interface properties cannot be accessed for binding purposes, nor can protected, private, internal, or virtual properties that have no base implementation

Solution 2

If you really really wanted to do this, you would have to provide a custom type descriptor, by implementing ICustomTypeDescriptor - that provides the extra property via a custom PropertyDescriptor alongisde the regular public properties. You can implement this interface on the type itself, or via TypeDescriptionProvider; the latter is preferred, as it works in more scenarios (things like empty lists, without needing to also provide a custom list with an ITypedList implementation). This is a lot of work, and it really isn't worth it except in extreme cases. But it can be done.

Solution 3

This is not possible, if you'd like, you could use internal instead.

... and use ObservableCollection<T> and don't forget to set the DataContext of the view.

Solution 4

You need a Relative Source binding, right now your binding is to the DataContext of your ItemBuySellAddEdit (FrameworkElement) Atleast that is my Impression, because you are using partial. If it is an ViewModel check the Output Window, and look if you have any binding errors.

<ComboBox 
    x:Name="xxx" 
    ItemsSource="{Binding Items, 
        RelativeSource={RelativeSource AncestorType={x:Type ItemBuySellAddEdit}},
        Mode=OneWay}"
    DisplayMemberPath="ItemName"/>

But the Answer from Stephan Bauer still applies.

Also Take the answer from WaltiD into consideration if you want new items in that list to show up automatically.

Share:
12,068
Admin
Author by

Admin

Updated on June 14, 2022

Comments

  • Admin
    Admin almost 2 years

    How to bind WPF an ItemsSource to a private property?

    <ComboBox x:Name="xxx" ItemsSource="{Binding Items, Mode=OneWay}"
              DisplayMemberPath="ItemName"/>
    
    public partial class ItemBuySellAddEdit : BasePage
    {
        private List<Item> Items { get; set; }
    }
    

    Items list will be populated while the form loads.

  • Stephan Bauer
    Stephan Bauer over 12 years
    Use ObservableCollection<T> instead of List<T>
  • Neutrino
    Neutrino about 12 years
    In my experience even internal accessibility is enough to break XAML data binding and only public properties can be bound to.