我對編程非常陌生。嘗試瞭解使用本教程的MVVM的基本思想http://social.technet.microsoft.com/wiki/contents/articles/13536.easy-mvvm-examples-in-extreme-detail.aspxINotifychanged接口的用途
我從此代碼中刪除了接口「:INotifypropertychanged」(刪除了這些詞)。仍然這個程序運行並按預期運行。那麼他在這裏INotifyPropertychanged的目的是什麼?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Windows;
using System.Windows.Threading;
namespace MvvmExample.ViewModel
{
class ViewModelBase : INotifyPropertyChanged
{
//basic ViewModelBase
internal void RaisePropertyChanged(string prop)
{
if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(prop)); }
}
public event PropertyChangedEventHandler PropertyChanged;
//Extra Stuff, shows why a base ViewModel is useful
bool? _CloseWindowFlag;
public bool? CloseWindowFlag
{
get { return _CloseWindowFlag; }
set
{
_CloseWindowFlag = value;
RaisePropertyChanged("CloseWindowFlag");
}
}
public virtual void CloseWindow(bool? result = true)
{
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
{
CloseWindowFlag = CloseWindowFlag == null
? true
: !CloseWindowFlag;
}));
}
}
}
WPF Binding檢查綁定的源對象是否實現了接口。它的確如此,Binding爲PropertyChanged事件附加了一個處理程序,以獲得有關屬性更改的通知。如果沒有接口聲明,事件仍然存在並觸發,但綁定不會被註冊爲偵聽器,也不會被更新。 – Clemens