简体   繁体   中英

How to bind an ItemsSource to a private property

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.

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

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM