[英]INotifyPropertyChanged with Properties that have the same name
我正在研究一種表示數據的系統。 在其中,我們使用實現INotifyPropertyChanged
的模板化接口。
public interface IScalar<T> : ISignal, INotifyPropertyChanged
{
void Check(T value);
/// <summary>
/// Formats the specified value based on the item's formatting
/// characteristics. Will throw an exception if the specified value
/// could not be properly converted to the underlying type.
/// </summary>
/// <param name="value">Value to format.</param>
/// <returns>Formatted value.</returns>
string Format(T value);
T Value { get; set; }
string Units { get; set; }
}
我們結束了一個實現IScalar<double>
和IScalar<string>
。 有沒有辦法確保觸發正確的PropertyChanged事件? 它使用屬性名稱的字符串表示形式。 而且由於我有兩個具有相同名稱的屬性,所以我不能保證會觸發正確的事件。 我們希望將WPF中的網格綁定到IScalar列表
您的數據上下文中不能有兩個具有相同名稱的屬性。 如果這樣做,將會產生反映歧義的編譯錯誤。
請記住,您的來源就是您的數據上下文。
另外,數據綁定系統依賴於源和路徑以執行數據綁定。
您不能使用兩個不同的類型參數隱式實現通用接口。 您必須至少顯示一個。 在這里,您將看到該類的示例實現。 如您所見,您可以綁定到StringValue
和DoubleValue
:
public class Both : IScalar<string>, IScalar<double>
{
public string StringValue { get; set; }
string IScalar<string>.Value
{
get
{
return StringValue;
}
set
{
this.StringValue = value;
}
}
public double DoubleValue { get; set; }
double IScalar<double>.Value
{
get
{
return DoubleValue;
}
set
{
DoubleValue = value;
}
}
// other methods and properties left out
}
當需要引發PropertyChanged
,可以為StringValue
或DoubleValue
引發該事件。
除了Scott的正確答案之外,您可能還希望通過傳入字符串來避免調用PropertyChanged方法。 這樣做的方法如下:
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
System.runtime.compilerservices程序集中的屬性類CallerMemberName現在支持使用成員/方法名稱的INPC。
您可以在此處了解更多信息。
優點:它使您可以輕松地一勞永逸地建立基類,並一勞永逸地處理僅基於方法名稱的所有通知。 setter方法僅具有以下代碼行:
OnPropertyChanged();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.