serious
serious

Reputation: 564

How to bind a string from singleton in xaml (WinRT / C#)

i've created a Singleton which contains a string. Now i want to bind this string to a TextBlock an Xaml.

<TextBlock Visibility="Visible" Text="{Binding singleton.Instance.newsString, Mode=TwoWay}"/>

When i run the WinRT App, the TextBlock-Text-String is empty.

EDIT 1:

Now it runs. But when i change the string in the singleton the TextBlock does not update.

Here is the c# code from my singleton

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;
    }
}

In my code behind the xaml i do this

        singleton.Instance.newsString = "Breaking news before init";
        this.Resources.Add("newsStringResource", singleton.Instance.newsString);
        this.InitializeComponent();
        singleton.Instance.newsString = "Breaking news AFTER init";

and in the xaml i bind the Resource with

        <TextBlock Visibility="Visible" Text="{StaticResource newsStringResource}" />

With this code the TextBlock shows "Breaking news before init". Whats wrong now?

Upvotes: 1

Views: 1167

Answers (1)

Filip Skakun
Filip Skakun

Reputation: 31724

Add your singleton to app resources using code behind before the TextBlock is constructed and reference the singleton by key.

Upvotes: 2

Related Questions