【发布时间】:2015-01-17 09:01:23
【问题描述】:
我对 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}" />
在 ListBox 中,我得到了正确的标签和组合框。但是组合框只是空的,因为它找不到要绑定的 AnimalStuff 列表。我尝试将绑定 RelativeSource 设置为各种设置,但我似乎无法让它在 C# 代码中找到列表。
有什么想法吗?
【问题讨论】:
-
ListBox 的
ItemsSource是什么? -
我没有。当我尝试添加它时,我收到此消息:使用 ItemsSource 之前,Items 集合必须为空。
-
这意味着您为您的 ListBox 手动添加了一些项目,那么它们是什么?
-
我有这段代码让 ListBox 出现在代码中:
.Items.Add(new Object());删除它允许它运行。但是如何为具有多个控件的 ListBox 创建 ItemsSource?
标签: c# wpf xaml binding datatemplate