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.
A binding source is usually a property on an object so you need to provide both the data source object and the data source property in your binding XAML. In the above example the ElementName attribute signifies that you want data from another element on the page and the Path signifies the appropriate property.
ItemsSource can be data bound to any sequence that implements the IEnumerable interface, although the type of collection used does determine the way in which the control is updated when items are added to or removed. When ItemsSource is set, the Items property cannot be used to control the displayed values.
The DataContext property is the default source of your bindings, unless you specifically declare another source, like we did in the previous chapter with the ElementName property. It's defined on the FrameworkElement class, which most UI controls, including the WPF Window, inherits from.
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With