我想在XAML中定義ItemsControl
的ItemsSource
,並且在這些項目中使用數據綁定到我的視圖的DataContext
,但我無法使其工作。在XAML中定義的ItemsSource中進行綁定
下面是一個簡化版本會是什麼樣子:
<ComboBox DisplayMemberPath="Label" DataContext="Item 3">
<ComboBox.ItemsSource>
<x:Array Type="{x:Type local:Item}">
<local:Item Label="Item 1" />
<local:Item Label="{Binding}" />
</x:Array>
</ComboBox.ItemsSource>
</ComboBox>
,像這樣定義的Item
:
public class Item : DependencyObject
{
public static readonly DependencyProperty LabelProperty =
DependencyProperty.Register(nameof(Label), typeof(string), typeof(Item));
public string Label
{
get { return (string)GetValue(LabelProperty); }
set { SetValue(LabelProperty, value); }
}
}
我期待看到「項目1」的組合框的兩個項目和「項目2」作爲文本,但第二項具有空白文本。爲什麼?
什麼是這些項目的DataContext?什麼是'DataContext =「Item 3」',你想讓DataContext成爲一個字符串?我不明白。讓你的viewmodel公開一個'ObservableCollection- Items {get; }'並將其綁定到'ItemsSource'? –
埃德擊敗了我......我相信'{綁定}'將綁定到您的DataContext的根,這是對象Item3。除非Item3是一個字符串,否則您將無法獲得有意義的標籤。 '{綁定標籤}'將綁定到Item3的Label屬性... –
這是一個過分簡化的示例,這就是它看起來很愚蠢的原因。在我的應用程序中,DataContext確實是一個視圖模型,我的項目由一個代表圖標,一個標籤,全部靜態並在XAML中定義的路徑組成。對於其中的兩個項目,我想添加一個視圖模型中的數字。我當然可以在視圖模型中創建可觀察的集合,但我不喜歡設置路徑以在視圖模型中生成圖標的想法。我真的覺得它屬於這個觀點,但也許我錯了。它更有意義嗎? –