我有这个组合框
<ComboBox Height="30" SelectedIndex="0" Margin="5 3 5 3" Width="170" ItemsSource="{Binding WonderList}" SelectedValuePath="selectedWonder">
<ComboBox.ItemTemplate>
<DataTemplate>
<WrapPanel>
<Image Source="{Binding Path}" Height="20"></Image>
<Label Content="{Binding Name}" Style="{StaticResource LabelComboItem}"></Label>
</WrapPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
我希望将项目显示为图像和文本 .
这是项列表中对象的业务类
public class Wonder: INotifyPropertyChanged
{
private string name;
private string path;
public event PropertyChangedEventHandler PropertyChanged;
#region properties, getters and setters
public String Name { get; set; }
public String Path { get; set; }
#endregion
public Wonder(string name, string path)
{
this.name = name;
this.path = path;
}
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
和窗口背后的代码
public class Window1 {
public List<Wonder> WonderList;
public Window1()
{
InitializeComponent();
WonderList = new List<Wonder>();
WonderList.Add(new Wonder("Alexandria", "Resources/Images/Scans/Wonders/Alexandria.jpg"));
WonderList.Add(new Wonder("Babylon", "Resources/Images/Scans/Wonders/Babylon.jpg"));
}
}
我对这个xaml "magic"很新,并且猜我没有正确理解数据绑定是如何工作的,我认为使用 ItemsSource="{Binding WonderList}"
它应该采用具有该名称的集合(来自后面的代码)并显示它们的名称和路径,但它显示一个空列表 .
如果我在后面的代码中执行 Combo1.ItemsSource = WonderList;
(我更喜欢使用xaml并避免代码隐藏),它会显示两个空白插槽,但仍然不知道如何显示这些项目 .
你能为我指出正确的方向吗?
谢谢
2 回答
如果你想像这样绑定
ItemsSource="{Binding WonderList}"
,你必须先设置DataContext .然后Binding将在Window1中找到WonderList,但前提是它也是属性 .
下一步:如果将值分配给私有字段名称,则绑定到属性Name是没用的 . 用你的构造函数替换
下一步:您的自动属性(
{ get; set; }
)不会通知更改 . 为此,你必须在setter中调用OnPropertyChanged
. 例如WonderList也是一样 . 如果你在构造函数中创建List to late,那么所有绑定都已经解决,你什么也看不见 .
最后使用ObservableCollection如果您想要通知新列表,而不是列表中添加的新项目 .
你没有做正确的方法 . 简单地说,你应该有一个Wonders类,它包含一个ObservableCollection属性,该属性绑定到ComboBox的ItemsSource . 你应该阅读MSDN:
http://msdn.microsoft.com/en-us/library/ms752347.aspx