wpf - 单个值的 INotifyPropertyChanged 与 ObservableCollection

标签 wpf mvvm static observablecollection inotifypropertychanged

在使用 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"对于 MyClassText[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 cause ObservableCollection 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/

相关文章:

wpf - WPF XAML中Border中每一边的颜色不同?

wpf - Panel.Children 与 Panel.InternalChildren - 有什么区别?

wpf - 如何使用 MVVM 从 WPF 对话框中获取值

c# - xaml无法识别模型的属性(WPF MVVM)

c++ - 当两个成员都在同一个类中时出现错误 "a nonstatic member reference must be relative to a specific object"

java - 静态初始化 block 的替代方案是什么?

java - 实例的输出ID

wpf - XAML 中的数据触发器/样式快速

json - Knockout.js遍历表中父级的子级

c# - 单元格编辑后 DataGrid 刷新