[英]C# WPF INotifyPropertyChanged not updating form
我正在嘗試使用基於用戶輸入的一些計算來實現一個表單。 使用 MVVM 模式,特別是 INotifyPropertyChanged。
當用戶在文本框中輸入一個值、計算例程觸發並且表單隨結果更新時,一切都運行良好。
但是,當從代碼隱藏更改輸入時,Inotify 例程會觸發,計算完成,但綁定控件不會更新。
我有兩個問題:
我附上了代碼的精簡版本,但這並不是我認為的真正問題。 注意我使用的是 singleton class。
謝謝
================
//INotify code
using s = Calc.Models.GlobalStrings;
namespace Calc.ViewModels.INotify
{
public class UcIOChanged : INotifyPropertyChanged
{
private static UcIOChanged instance;
public UcIOChanged() { }
//Make the class is a singleton
public static UcIOChanged Instance
{
get
{
if (instance == null)
{
instance = new UcIOChanged();
}
return instance;
}
}
public event PropertyChangedEventHandler PropertyChanged;
public string Pressure
{
get
{
return s.Pressure;
}
set
{
s.Pressure = value; OnPropertyChanged();
}
}
public void OnPropertyChanged()
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Pressure)));
}
}
}
注意我使用的是 singleton class。
這段代碼沒有錯誤。 但是您可能使用不正確。 為避免意外使用錯誤,我建議您更改實現:
public class UcIOChanged
{
// Hide the constructor to avoid
// accidentally creating other instances.
private UcIOChanged() {}
//Make the class is a singleton
public static UcIOChanged Instance { get; } = new UcIOChanged();
public string Pressure
{
get
{
return s.Pressure;
}
set
{
if (!Equals(s.Pressure, value))
{
s.Pressure = value;
PressureChanged?.Invoke(this, EventArgs.Empty);
}
}
}
// The event of the same name.
// It's easier for one or two properties
// than the INotifyPropertyChanged implementation.
public event EventHandler PressureChanged;
}
使用:
<TextBox Text="{Binding Pressure, Source={x:Static local:UcIOChanged.Instance}}"/>
PS如果您在代碼中的某個位置(而不是通過 UcIOChanged.Instance 的實例)更改s.Pressure
,則正確操作可能會受到影響。
因此,您必須確保只有在通知其更改時才能訪問此變量(屬性或字段?)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.