3

在使用MVVM模式和WPF綁定進行編碼的示例中,它們在單值時使用INotifyPropertyChanged,在爲值列表時使用ObservableCollectionINotifyPropertyChanged vs ObservableCollection對於單個值

我也讀過,你不能使用靜態變量INotifyPropertyChanged,但你可以用ObservableCollection。我想綁定到一個靜態變量。

最簡單的方法(對我來說至少)解決方法是使用ObservableCollection,並且始終只使用並綁定到索引0.這適合做什麼?使用INotifyPropertyChanged而不是ObservableCollection有什麼好處?

例如: 這似乎是最簡單的解決方法:

public static ObservableCollection<int> MyValues { get; set; } 

<TextBox Text="{Binding MyValue[0]}"> 

對於想做到這一點:

private static int _myValue; 
public static int MyValue //does not work 
{ 
    get { return _myValue; } 
    set { _myValue = value; OnPropertyChange(); } 
} 

<TextBox Text="{Binding MyValue, UpdateSourceTrigger=PropertyChanged}"> 
+0

「這適合做什麼?」如果它有效,那麼它就可以工作。只要你沒有遇到任何性能問題,那麼我認爲它是好的。因爲就像你說的那樣,你不能在INotifyPropertyChanged中使用靜態屬性。我不知道通過ObservableCollection使用INPC的好處,因爲它們通常以不同的方式使用,但在這種情況下,您無法在靜態屬性中使用INPC。 – Zack

+0

你也可能會對這個問題的接受的答案感興趣http://stackoverflow.com/questions/14614190/inotifypropertychanged-and-static-properties – Zack

+0

你可以在理論上改變通知與靜態屬性('公共靜態事件EventHandler StaticPropertyChanged',等等)但是...我已經嘗試過了,它沒有工作,而且你的黑客看起來更少麻煩,而且實際上可以工作。謝謝! –

回答

1

我不認爲你的比喻是公平的(直接與Primitive Type屬性比較ObservableCollection)。比較ObservableCollection下面類

public class MyClass : INotifyPropertyChanged 
{ 

    private string text; 

    public string Text 
    { 
     get { return text; } 
     set { text = value; 
     RaiseChange("Text"); 
     } 
    } 


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

現在下面都將表現相同:

public static MyClass Text { get; set; } 

public static ObservableCollection<string> Text { get; set; } 

如果您MyClassText[0] = "Hello"ObservableCollection執行Text.Text = "Hello",都將體現在同樣的方式。

現在,如果你必須使用一個靜態屬性綁定,然後,而不是ObservableCollection我會建議你寫你的新類 原因ObservableCollection有許多內部實現這 可能是沒有用的,你的任何實際上消耗內存& perforamnce。

0

link可能會有所幫助,它顯示列表,的ObservableCollection之間的差異INotifyPropertyChanged的。

希望這有助於

相關問題