1
我创建了一个包含字符串的单例。 现在我想将这个字符串绑定到一个XAML的TextBlock。如何从xaml中的单例中绑定字符串(WinRT/C#)
<TextBlock Visibility="Visible" Text="{Binding singleton.Instance.newsString, Mode=TwoWay}"/>
当我运行WinRT应用程序时,TextBlock-Text-String为空。
编辑1:
现在它运行。但是,当我改变单身字符串中的TextBlock不更新。
这里是我的单身
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;
}
}
C#代码在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显示“init之前的突发新闻”。 现在怎么了?
感谢您的咨询!但现在出现了另一个问题。看看“Edit1” – 2013-02-15 22:18:47
你没有绑定资源,你基本上设置了一个资源。你需要将单例的实例设置为资源,然后执行'Text =“{Binding DownloadMgrString,Source = {StaticResource MySingletonResourceKey}”' – 2013-02-16 00:58:05