views:

430

answers:

1
ItemsSource="{Binding Source={StaticResource stringResources}, Path=MyProp}"

I tried and got so far but I don't get it compiled:

comboBox.ItemsSource = new Binding { Source = new StringResources(), ElementName = "MyProp" };
comboBox.DisplayMemberPath="Value";
comboBox.SelectedValuePath="Key";

It says that it cannot convert Binding to IEnumerable and I wasn't sure how to construct a PropertyPath so I used ElementName but I don't know if this is the same.

StringResources is a class which has a property MyProp which returns a Dictionary.

+2  A: 
var binding = new Binding("MyProp") { Source = new StringResources() };
BindingOperations.SetBinding(comboBox, ComboBox.ItemsSourceProperty, binding);

As an alternative to using BindingOperations, you could also use the SetBinding method on the ComboBox class.

In the interests of teaching you how to fish, your code was trying to assign the Binding instance directly to the ItemsSource property (which only takes objects of certain types, including IEnumerable). You need to use WPF's binding engine to translate your source into something that the target property can consume. In this case, it's translating or surfacing the MyProp property on an instance of StringResources to an enumeration that is then consumed by the ItemsSource property.

HTH, Kent

Kent Boogaart
Thanks it works great now! I also noticed that it is very important to assign DisplayMemberPath and SelectedValuePath *before* the binding is added, otherwise it won't work.
codymanix