1 回答

TA貢獻1963條經驗 獲得超6個贊
準備基礎代碼 1 創建一個ViewModelBase publicabstractclassViewModelBase:INotifyPropertyChanged{ //屬性改變事件 publiceventPropertyChangedEventHandlerPropertyChanged; //當屬性改變的時候,調用該方法來發起一個消息,通知View中綁定了propertyName的元素做出調整 publicvoidRaisePropertyChanged(stringpropertyName) { PropertyChangedEventHandlerhandler=PropertyChanged; if(handler!=null) { handler(this,newPropertyChangedEventArgs(propertyName)); } } } 2 創建一個DelegateCommand publicclassDelegateCommand:ICommand{ readonlyAction_execute; readonlyPredicate_canExecute; publicDelegateCommand(Actionexecute) :this(execute,null) { } publicDelegateCommand(Actionexecute,PredicatecanExecute) { if(execute==null) thrownewArgumentNullException("execute"); _execute=execute; _canExecute=canExecute; } publicvoidExecute(objectparameter) { _execute(parameter); } publicboolCanExecute(objectparameter) { return_canExecute==null?true:_canExecute(parameter); } publiceventEventHandlerCanExecuteChanged { add{CommandManager.RequerySuggested+=value;} remove{CommandManager.RequerySuggested-=value;} } } END 創建示例用ViewModel 讓ViewModel繼承自ViewModelBase?! ublicclassMainWindowViewModel:ViewModelBase{ privatestring_input; publicstringInput { get { return_input; } set { _input=value; RaisePropertyChanged("Input"); } } privatestring_display; publicstringDisplay { get { return_display; } set { _display=value; RaisePropertyChanged("Display"); } } publicDelegateCommandSetTextCommand{get;set;} privatevoidSetText(objectobj) { Display=Input; } publicMainWindowViewModel() { SetTextCommand=newDelegateCommand(newAction(SetText)); } } END 創建View 最少只需要三個控件:一個textbox拿來做輸入,一個label拿來做輸出,一個button拿來提交數據?! ND 綁定View和ViewModel 當View和ViewModel都已經創建完之后,最后一步就是把它哥倆綁定在一起了。這樣,當View改變的時候,ViewModel就會發生相應的改變,反之亦然。
- 1 回答
- 0 關注
- 818 瀏覽
添加回答
舉報