2013-06-23 33 views
1

我有这样的组合框绑定集合,组合框

<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")); 
    } 
} 

I'm很新,此XAML“神奇”的后面的代码公务舱和猜测我不明白数据绑定是如何工作的,我认为使用ItemsSource="{Binding WonderList}"它应该使用该名称的集合(来自代码背后)并显示它们的名称和路径,但它显示一个空列表。

如果我在后面的代码中使用Combo1.ItemsSource = WonderList;(我更喜欢使用xaml并避免后面的代码),它显示两个空白插槽,但仍不知道如何显示这些项目。

您能否指点我正确的方向?

谢谢

回答

2

:你应该阅读MSDN。

public Window1() 
{ 
    ... 
    this.DataContext = this; 
} 

然后,绑定将在Window1中找到WonderList,但前提是它也是属性。

public List<Wonder> WonderList { get; private set; } 

Next:如果将值赋给私有字段名称,则无法绑定到属性名称。与

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