2013-03-06 264 views
3

這裏我添加了一個模型,我的ViewModel ...我怎樣才能RaisePropertyChanged屬性更改?

public dal.UserAccount User { 
    get 
    { 
    return _user; 
    } 
    set 
    { 
    _user = value; 
    RaisePropertyChanged(String.Empty); 
    } 
} 

我辦理產權變更事件......

public event PropertyChangedEventHandler PropertyChanged; 
private void RaisePropertyChanged(string propertyName) 
{ 
    if (this.PropertyChanged != null) 
    this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
} 

這是我使用的綁定。

<TextBox Text="{Binding User.firstname, Mode=TwoWay, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" /> 

問題是propertychange事件不會觸發更新視圖?任何人都可以告訴我我做錯了什麼...

+0

你必須把你的變量名,以它的參數,而不是'string.Empty'。你可以將你的'RaisePropertyChanged'方法原型設爲'void RaisePropertyChanged([CallerMemberName] string propertyName = null)',並且不向其發送參數,所以你的調用者名稱將被用作參數值。 – 2016-04-19 11:31:08

回答

7

PropertyChanged用於通知UI模型中的某些內容已被更改。 由於您正在更改內部屬性用戶對象 - User屬性本身未更改,因此不會引發PropertyChanged事件。

秒 - 您的型號should implement the INotifyPropertyChanged interface。 - 換句話說,確保UserAccount實現INotifyPropertyChanged,否則更改firstname也不會影響視圖。

另一件事:

參數RaisePropertyChanged應該接受的是名稱已更改屬性的。所以你的情況:

變化:
RaisePropertyChanged(String.Empty);


RaisePropertyChanged("User");

MSDN

PropertyChanged事件可以指示對象所有的屬性都通過使用改變null或String.Empty作爲PropertyChangedEventArgs中的屬性名稱。

(無需刷新所有在這種情況下,屬性)

你可以閱讀更多的概念的PropertyChangedhere

+0

我這樣做,但這不工作,因爲在文本框中綁定爲User.firstname ... – 2013-03-06 11:33:02

+0

是的,我補充說:) – 2013-03-06 11:36:44

+0

請閱讀我更新的答案 – Blachshma 2013-03-06 11:37:14

0

您可以從另一個類中調用一個屬性更改事件。如果您擁有所有資源,則不是特別有用。對於封閉的來源,它可能是。雖然我不認爲它是實驗性的,而不是生產準備。

看到這個控制檯複製粘貼例如:

using System; 
using System.ComponentModel; 
using System.Runtime.InteropServices; 

namespace ConsoleApp1 
{ 
    public class Program 
    { 
     static void Main(string[] args) 
     { 
      var a = new A(); 
      a.PropertyChanged += A_PropertyChanged; 
      var excpl = new Excpl(); 
      excpl.Victim = a; 
      excpl.Ghost.Do(); 
     } 

     private static void A_PropertyChanged(object sender, PropertyChangedEventArgs e) 
     { 
      Console.WriteLine("Event triggered"); 
     } 
    } 

    [StructLayout(LayoutKind.Explicit)] 
    public struct Excpl 
    { 
     [FieldOffset(0)] 
     public A Victim; 
     [FieldOffset(0)] 
     public C Ghost; 
    } 

    public class A : INotifyPropertyChanged 
    { 
     public event PropertyChangedEventHandler PropertyChanged; 
    } 

    public class C : INotifyPropertyChanged 
    { 
     public event PropertyChangedEventHandler PropertyChanged; 

     public void Do() 
     { 
      PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("")); 
     } 
    } 
}