开发者

how to express this xaml combobox data-binding in c# code

ItemsSource="{Binding So开发者_高级运维urce={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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜