[英]how to express this xaml combobox data-binding in c# code
ItemsSource="{Binding Source={StaticResource stringResources}, Path=MyProp}"
我尝试了到现在为止,但是我没有编译它:
comboBox.ItemsSource = new Binding { Source = new StringResources(), ElementName = "MyProp" };
comboBox.DisplayMemberPath="Value";
comboBox.SelectedValuePath="Key";
它说它不能将Binding转换为IEnumerable,而且我不确定如何构造PropertyPath,所以我使用了ElementName,但我不知道这是否相同。
StringResources是一个具有属性MyProp的类,该属性返回Dictionary。
var binding = new Binding("MyProp") { Source = new StringResources() };
BindingOperations.SetBinding(comboBox, ComboBox.ItemsSourceProperty, binding);
除了使用BindingOperations
,还可以在ComboBox
类上使用SetBinding
方法。
为了教您如何钓鱼,您的代码尝试将Binding
实例直接分配给ItemsSource
属性(该属性仅采用某些类型的对象,包括IEnumerable
)。 您需要使用WPF的绑定引擎将源转换为目标属性可以使用的内容。 在这种情况下,它MyProp
StringResources
实例上的MyProp
属性转换或显示为枚举,然后由ItemsSource
属性使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.