【问题标题】:How to bind a string from singleton in xaml (WinRT / C#)如何在 xaml 中从单例绑定字符串(WinRT / C#)
【发布时间】:2013-01-31 14:52:33
【问题描述】:

我创建了一个包含字符串的单例。 现在我想将此字符串绑定到 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 会显示“初始化前的突发新闻”。 现在怎么了?

【问题讨论】:

    标签: xaml binding windows-runtime


    【解决方案1】:

    在构造 TextBlock 之前使用后面的代码将您的单例添加到应用程序资源并按键引用单例。

    【讨论】:

    • 感谢您的建议!但是现在又出现了一个问题。看“Edit1”
    • 您没有绑定资源,您基本上设置了资源。您需要将单例的实例设置为资源,然后执行Text="{Binding DownloadMgrString, Source={StaticResource MySingletonResourceKey}"
    猜你喜欢
    • 1970-01-01
    • 2014-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-01
    相关资源
    最近更新 更多