将集合绑定到组合框
本文关键字:组合 绑定 集合 | 更新日期: 2023-09-27 18:19:31
我有这个组合框
<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"魔术"还很陌生,我想我不正确理解数据绑定是如何工作的,我认为使用ItemsSource="{Binding WonderList}"
,它应该使用该名称的集合(从后面的代码中)并显示它们的名称和路径,但它显示的是一个空列表。
如果我在代码隐藏中执行Combo1.ItemsSource = WonderList;
(我更喜欢使用xaml并避免代码隐藏),它会显示两个空白插槽,但仍然不知道如何显示项目。
你能给我指正确的方向吗?
感谢
如果要像这样绑定ItemsSource="{Binding WonderList}"
,必须先设置DataContext
。
public Window1()
{
...
this.DataContext = this;
}
绑定会在Window1中找到WonderList,但前提是它也是一个属性。
public List<Wonder> WonderList { get; private set; }
下一步:如果您将值分配给私有字段名称,那么绑定到属性Name是没有用的。用替换您的构造函数
public Wonder(string name, string path)
{
this.Name = name;
this.Path = path;
}
下一步:您的自动属性({ get; set; }
)不会通知更改。为此,您必须在setter中调用OnPropertyChanged
。例如
public String Name
{
get { return name; }
set
{
if (name == value) return;
name = value;
OnPropertyChanged("Name");
}
}
WonderList也是如此。如果在构造函数的后期创建List,则可能是所有绑定都已解析,并且什么也看不到。
最后,如果您不想通知新列表,而是想通知列表中新添加的项目,请使用ObservableCollection
。
您的操作方式不正确。简单地说,您应该有一个Wonders类,它持有一个ObservableCollection属性,该属性绑定到ComboBox的ItemsSource。您应该阅读MSDN:
http://msdn.microsoft.com/en-us/library/ms752347.aspx