2009-10-25 25 views
0
ItemsSource="{Binding Source={StaticResource stringResources}, Path=MyProp}" 

我試過找來至今的數據綁定,但我不明白編譯:如何表達這個XAML組合框在C#代碼

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

它說,它不能轉換結合IEnumerable和我不知道如何構建一個PropertyPath,所以我使用了ElementName,但我不知道這是否相同。

StringResources是一個具有屬性MyProp的類,它返回一個Dictionary。

回答

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

作爲替代使用BindingOperations,你也可以使用在ComboBoxSetBinding方法。

在教你如何釣魚的利益,你的代碼試圖在Binding實例都可以直接分配給ItemsSource屬性(只需要某些類型的,包括IEnumerable的對象)。您需要使用WPF的綁定引擎將您的源代碼轉換爲目標屬性可以使用的內容。在這種情況下,它將StringResources的實例上的MyProp屬性轉換或呈現給枚舉,然後由ItemsSource屬性使用該枚舉。

+0

感謝它現在很好用!我還注意到,在添加綁定之前分配DisplayMemberPath和SelectedValuePath *非常重要,否則它將不起作用。 – codymanix 2009-10-25 20:09:03