ListBox ItemsSource绑定通过代码但不通过XAML

时间:2011-01-13 07:52:23

标签: windows-phone-7 silverlight-3.0 binding

我有这个XAML:

<ListBox x:Name="MyItemsList"                         
     ItemsSource="{Binding MyItems}" 
     SelectionChanged="ItemsList_SelectionChanged">

后面的代码将页面的datacontext分配给视图模型:

DataContext = App.ViewModel;

我的ViewModel对象定义MyItems(我在设置DataContext之前初始化MyItems):

public ObservableCollection<Item> MyItems;

最终结果是我的ListBox没有显示任何内容。我尝试在绑定后添加项目,但它们也没有出现。

如果我在代码中而不是在XAML中设置ItemsSource是有效的:

MyItemsList.ItemsSource = App.ViewModel.MyItems;

有关为何会发生这种情况的任何提示?感谢。

1 个答案:

答案 0 :(得分:2)

public ObservableCollection MyItems; - 田野,但你应该使用财产!

具有支持字段的属性:

private ObservableCollection<Item> _myItems = new ObservableCollection<Item>();
public ObservableCollection<Item> MyItems{get{return _myItems;}}

如果您打算使用setter,则应实现INotifyPropertyChanged并调用OnPropertyChanged(“MyItems”)