【发布时间】:2011-09-04 16:21:48
【问题描述】:
我是 WP7 应用程序的开发人员。 有谁知道如何在 ViewModel 类中将数据绑定到 ListBox.ItemSource 的想法?
【问题讨论】:
标签: windows-phone-7 silverlight-4.0
我是 WP7 应用程序的开发人员。 有谁知道如何在 ViewModel 类中将数据绑定到 ListBox.ItemSource 的想法?
【问题讨论】:
标签: windows-phone-7 silverlight-4.0
<ListBox ItemsSource={Binding ViewModelPropertyName}" />
ViewModelPropertyName 应该返回 IList 或更好。
如果要显示对集合的更改,它应该返回一个INotifyCollectionChanged,例如ObservableCollection<T>。
<ListBox ItemsSource={Binding ViewModelPropertyName}" />
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text={Binding PropertyNameWithinObject} />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
【讨论】:
在上面的同一个例子中,你需要在类中定义绑定名称“ViewModelPropertyname”
示例:类名称为“模型”
int _PropertyNameWithinObject;
public int PropertyNameWithinObject
{
get
{
return PropertyNameWithinObject;
}
set
{
PropertyNameWithinObject= value;
OnPropertyChanged("PropertyNameWithinObject");
}
}
在“模型”类中包含以下类
public class ViewModelBaseEx : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
然后在另一个名为“ViewModel”的整洁类中定义集合
ObservableCollection<Model> _ViewModelPropertyName= new ObservableCollection<Model>();
public ObservableCollection<Model> ViewModelPropertyName
{
get
{
return _ViewModelPropertyName;
}
set
{
_ViewModelPropertyName= value;
OnPropertyChanged("ViewModelPropertyName");
}
}
对于以下绑定
<ListBox ItemsSource={Binding ViewModelPropertyName}" />
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text={Binding PropertyNameWithinObject} />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
并在 c# 或设计中在此页面的 datacontext 中分配类“ViewModel”,这里我在 c# 页面中声明, 喜欢
this.DataContext = ViewModel;
【讨论】: