为了方便我们定义一个ViewModelBase的抽象基类,然后让其他ViewModel继承这个基类。 ViewModelBase
public abstract class ViewModelBase : System.ComponentModel.INotifyPropertyChanged, IDisposable
{ public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) { var arg = new System.ComponentModel.PropertyChangedEventArgs(propertyName); PropertyChanged(this, arg); } } public virtual void Dispose() { } }
第二种是利用DependencyObject和DependencyProperty。 PeopleItemViewModel
public class PeopleItemViewModel : DependencyObject, IPeopleItemViewModel
{ public PeopleItemViewModel() { } public static readonly DependencyProperty SimpleUserDataProperty = DependencyProperty.Register("SimpleUserData", typeof(SimpleUserData), typeof(PeopleItemViewModel)); public static readonly DependencyProperty RelativeSimpleUserDataProperty = DependencyProperty.Register("RelativeSimpleUserData", typeof(ObservableCollection<SimpleUserData>), typeof(PeopleItemViewModel)); public static readonly DependencyProperty AllSimpleUserDataProperty = DependencyProperty.Register("AllSimpleUserData", typeof(ObservableCollection<SimpleUserData>), typeof(PeopleItemViewModel)); public SimpleUserData SimpleUserData { get { return (SimpleUserData)base.GetValue(SimpleUserDataProperty); } set { if (!base.CheckAccess()) { Dispatcher.Invoke(new Action( () => { SimpleUserData = value; })); } else base.SetValue(SimpleUserDataProperty, value); } } public ObservableCollection<SimpleUserData> RelativeSimpleUserData { get { return (ObservableCollection<SimpleUserData>)base.GetValue(RelativeSimpleUserDataProperty); } set { if (!base.CheckAccess()) { Dispatcher.Invoke(new Action( () => { RelativeSimpleUserData = value; })); } else { base.SetValue(RelativeSimpleUserDataProperty, value); var collectionView = CollectionViewSource.GetDefaultView(value); collectionView.SortDescriptions.Add(new SortDescription("Distance", ListSortDirection.Ascending)); } } } public ObservableCollection<SimpleUserData> AllSimpleUserData { get { return (ObservableCollection<SimpleUserData>)base.GetValue(AllSimpleUserDataProperty); } set { if (!base.CheckAccess()) { Dispatcher.Invoke(new Action( () => { AllSimpleUserData = value; })); } else { base.SetValue(AllSimpleUserDataProperty, value); var collectionView = CollectionViewSource.GetDefaultView(value); collectionView.SortDescriptions.Add(new SortDescription("Distance", ListSortDirection.Ascending)); } } } }
在View中绑定ViewModel。 为了方便,我们可以在app.xaml中将需要的viewmode放到全局资源字典中。 然后再我们的vs视图设计器Properties(中文版显示的是“属性”)页上选择为绑定源设置绑定目标(包括source和path等)以及必要的值转换器等等即可。 (PS:虽然vs很强大,但个人还是建议熟悉xaml的绑定语法,想当初用vs2008搞wpf的时候貌似还没有这么方便的设计器。。。) (责任编辑:admin) |