我创建了一个包含字符串的单例。现在我想将此字符串绑定到 TextBlock 和 Xaml。
<TextBlock Visibility="Visible" Text="{Binding singleton.Instance.newsString, Mode=TwoWay}"/>
当我运行 WinRT 应用程序时,TextBlock-Text-String 为空。
编辑1:
现在它运行了。但是当我更改单例中的字符串时,TextBlock 不会更新。
这是我单身人士的 c# 代码
namespace MyApp
{
public sealed class singleton : INotifyPropertyChanged
{
private static readonly singleton instance = new singleton();
public static singleton Instance
{
get
{
return instance;
}
}
private singleton() { }
private string _newsString;
public string newsString
{
get
{
if (_newsString == null)
_newsString = "";
return _newsString;
}
set
{
if (_newsString != value)
{
_newsString = value;
this.RaiseNotifyPropertyChanged("newsString");
}
}
}
private void RaiseNotifyPropertyChanged(string property)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(property));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
在我的 xaml 代码中,我这样做了
singleton.Instance.newsString = "Breaking news before init";
this.Resources.Add("newsStringResource", singleton.Instance.newsString);
this.InitializeComponent();
singleton.Instance.newsString = "Breaking news AFTER init";
在 xaml 中我将资源绑定到
<TextBlock Visibility="Visible" Text="{StaticResource newsStringResource}" />
使用此代码,TextBlock 会显示“初始化前的突发新闻”。现在怎么了?