在使用 MVVM 模式和 WPF 绑定(bind)进行编码的示例中,他们使用 INotifyPropertyChanged
当它是单个值和 ObservableCollection
当它是一个值列表时。
我也读过,你不能在 INotifyPropertyChanged
中使用静态变量。 , 但您可以使用 ObservableCollection
.我想绑定(bind)到一个静态变量。
最简单(至少对我而言)的解决方法是使用 ObservableCollection
并且总是只使用并绑定(bind)到索引 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}">
最佳答案
我不认为你的类比是公平的(比较 ObservableCollection
直接与 Primitive Type
属性)。比较 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; }
如果您执行
Text.Text = "Hello"
对于 MyClass
或 Text[0] = "Hello"
对于 ObservableCollection
,两者都会以同样的方式反射(reflect)。Now if you have to use a static property for binding then instead of
ObservableCollection
I'll advice you to write your new class causeObservableCollection
has many internal implementations which probably is of no use to you any actually consuming memory & perforamnce.
关于wpf - 单个值的 INotifyPropertyChanged 与 ObservableCollection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36802237/