2013-02-15 40 views
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之前的突發新聞」。 現在怎麼了?

回答

2

在構建TextBlock之前,使用後面的代碼將您的單例添加到應用程序資源中,並通過鍵引用單例。

+0

感謝您的諮詢!但現在出現了另一個問題。看看「Edit1」 – 2013-02-15 22:18:47

+0

你沒有綁定資源,你基本上設置了一個資源。你需要將單例的實例設置爲資源,然後執行'Text =「{Binding DownloadMgrString,Source = {StaticResource MySingletonResourceKey}」' – 2013-02-16 00:58:05

相關問題