[英]UWP Using x:Bind to monitor global variables
我有一個應用程序將所有全局變量分組到一個 class 中。 它們用於應用程序中的許多類。 (300 多個變量,為演示而縮短):
public class Vars
{
public static string DateStr = "";
}
我想使用 x:Bind to One-way 將數據綁定到頁面上的字段:
<TextBlock x:Name="Local_Data" Text="{x:Bind local:Vars.DateStr, Mode=OneWay}" Style="{StaticResource TextBlockStyle1}"/>
OneTime 綁定似乎工作正常。 我可以刷新頁面,並且 DateStr 反映了新值。
我將 Vars class 定義更改為:
public class Vars : INotifyPropertyChanged
{
private static string _DateStr = "hello";
public static string DateStr
{
get { return _DateStr; }
set
{
_DateStr = value;
OnPropertyChanged();
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Raises this object's PropertyChanged event.
/// </summary>
/// <param name="propertyName">The property that has a new value.</param>
protected void OnPropertyChanged([CallerMemberName]string propertyName = null)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
var e = new PropertyChangedEventArgs(propertyName);
handler(this, e);
}
}
#endregion
}
當我嘗試構建時,我收到消息:
非靜態字段、方法或屬性“Vars.OnPropertyChanged(string)”需要 object 引用
如果我將其更改為:
protected static void OnPropertyChanged([CallerMemberName]string propertyName = null)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
var e = new PropertyChangedEventArgs(propertyName);
handler(this, e);
}
}
我收到消息:
關鍵字“this”在 static 屬性、static 方法或 static 字段初始化程序中無效
我認為我錯過了一些微不足道的事情。 標記數據更改的正確方法是什么?
謝謝你的幫助。 擔
正如提到的錯誤消息,您的問題的原因是您使用Static
修飾符作為綁定源屬性Vars.DateStr
。 您只需要刪除Vars.DateStr
屬性的Static
修飾符。
public string DateStr
{
get { return _DateStr; }
set
{
_DateStr = value;
OnPropertyChanged("DateStr");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.