Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 942
sameera Avatar asked Sep 05 '11 10:09

sameera


People also ask

What is binding source in WPF?

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.

What is ItemsSource in XAML?

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.

What is DataContext in WPF?

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.


2 Answers

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.

like image 188
Marc Gravell Avatar answered Oct 28 '22 06:10

Marc Gravell


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

like image 25
Stephan Bauer Avatar answered Oct 28 '22 07:10

Stephan Bauer