[英]How can I bind ComboBox ItemSource in a DataTemplate to a List?
我對WPF,C#,XAML等非常陌生。但是我正在學習。 到目前為止,我在將DataTemplate中的ComboBox ItemSource綁定到C#字符串列表時遇到了麻煩。
這是我的C#代碼:
public class Giraffe {
...
public Zebra() {
AnimalStuff.Add("Head");
AnimalStuff.Add("Stripes");
AnimalStuff.Add("Tail");
}
private List<string> _animalStuff= new List<string>();
public List<string> AnimalStuff {
get { return _animalStuff; }
set {
_animalStuff= value;
OnPropertyChanged("AnimalStuff");
}
}
#region OnPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName) {
if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); }
}
#endregion
}
這是我的XAML代碼:
...
<Page.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="AnimalTemplates.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Page.Resources>
...
<ComboBox ItemsSource="{Binding AnimalStuff}" />
該部分工作完美。 我得到一個帶有所有AnimalStuff字符串下拉列表的組合框。
但是,我需要將該組合框放在DataTemplate中。 我無法工作。 這是DataTemplate文件:
...
<DataTemplate x:Key="AnimalTemplate">
<Grid x:Name="GridAnimalTemplate" >
...
<Label Content="Select Animal Part:" />
<ComboBox ItemsSource="{Binding AnimalStuff}" />
</Grid>
</DataTemplate>
我將此添加到XAML文件中:
<ListBox ItemTemplate="{DynamicResource AnimalTemplate}" />
在列表框,我得到正確的標簽和組合框出現。 但是組合框只是空的,因為它找不到要綁定的AnimalStuff列表。 我嘗試將綁定RelativeSource設置為各種設置,但似乎無法在C#代碼中找到它。
有任何想法嗎?
首先添加INotifyPropertyChanged
接口,然后看看會發生什么。
如果不起作用,也請點擊以下鏈接
取決於將項目添加到列表的時間以及將列表設置為ItemsSource
, ComboBox
可能不會反映對ItemsSource
更新。 使用ObservableCollection
而不是List
,看看是否可以解決您的問題。
國王國王使我走上了正確的軌道。
這是正確的答案:在C#代碼中,您需要創建一個新列表。
List<AnimalListboxItem>[ AnimalItems = new List<AnimalListboxItem>();
public class AnimalListboxItem{
public string AnimalPartLabel { get; set; }
public List<string> AnimalStuff{ get; set; }
}
然后使用該新列表作為列表框的項目源:
AnimalItems = new List<AnimalListboxItem>();
<listbox name>.Items.Add(new AnimalListboxItem
AnimalPartLabelBound = "Select Animal Part:",
AnimalStuffBound = AnimalStuff);
然后,您可以在XAML中進行綁定:
<DataTemplate x:Key="AnimalTemplate">
<Grid x:Name="GridAnimalTemplate" >
...
<Label Content="{Binding AnimalPartLabelBound}" />
<ComboBox ItemsSource="{Binding AnimalStuffBound}" />
</Grid>
</DataTemplate>
您可以在AnimalListboxItem類中放入任意數量的內容,包括數組,其他列表等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.