2014-01-21 63 views
1
public class ViewModel : INotifyPropertyChanged 
{ 
    private string name; 
    public string Name 
    { 
     get 
     { 
      return name; 
     } 
     set 
     { 
      if (name != value) 
      { 
       name = value; 
       OnPropertyChanged("Name"); 

      } 
     } 
    } 
    protected void OnPropertyChanged(string propertyname) 
    { 
     if (PropertyChanged != null) 
     { 
      PropertyChanged(this, new PropertyChangedEventArgs(propertyname)); 
     } 
    } 
    public PropertyChangedEventHandler PropertyChanged; 
} 

public partial class MainWindow : Window 
{ 
    private ViewModel vm; 
    public MainWindow() 
    { 
     InitializeComponent(); 
     vm = new ViewModel { Name = "Shahrukh Khan" }; 
     DataContext = vm; 
    } 

    private void Button_Click_1(object sender, RoutedEventArgs e) 
    { 
     vm.Name = "Salman Khan"; 
    } 
} 

當我運行下面的代碼我得到這個錯誤:INotifyPropertyChange接口錯誤

INotifyUnderstandingYoutube.ViewModel does not implement interface member System.ComponentModel.INotifyPropertyChanged.PropertyChanged

我不明白這背後的原因是什麼?任何人都可以請解釋什麼是錯誤?

回答

5

public PropertyChangedEventHandler PropertyChanged; 

PropertyChanged定義爲一個字段,而這恰好是委託類型的字段,但儘管如此。 INotifyPropertyChanged需要一個事件。

public event PropertyChangedEventHandler PropertyChanged; 
     ^^^^^ 
+0

是的,它現在工作很棒:) – TheSpy

0

這意味着你沒有完全實現接口。在接口聲明(之後:INotifyPropertyChanged)上,按Shift + Alt + F10,讓Visual Studio爲您添加代碼。然後你會看到你錯過了什麼。

好像你缺少這段代碼在你的ViewModel類:

event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged 
{ 
    add { throw new NotImplementedException(); } 
    remove { throw new NotImplementedException(); } 
}