将标签绑定到静态字符串 [英] Binding Label to a static string

查看:25
本文介绍了将标签绑定到静态字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个基本表单,它被应用程序中的大多数表单继承.基本表单包含一个状态栏控件,该控件显示用户名,该用户名在内部是一个静态字符串.

用户可以通过按下状态栏上的按钮在应用程序中的任何位置切换用户.此时状态栏的用户名也应该发生变化了,好像现在只是代码变化,UI不知道变化.我搜索了一下,发现我需要通过实现 INotifyProperty 接口来将标签与该静态字符串绑定.我已经实现了许多示例代码,但都没有成功.

I have made a Base Form which is inherited by most Forms in the application. Base form contains a Status Bar Control that displays user name which is internally a static string.

User can Switch User at any point in the application by pressing a button on status bar. At this point the user name in the status bar should also change, as if now it only changes in code and UI has no idea about the change. I have googled around and found that i need to bind the label with that static string by implementing a INotifyProperty Interface. I have implemented many example code without success.

感谢任何帮助

推荐答案

你必须实现一个类来通知 prop 改变,因此 prop 不能是静态的.结合单例模式,您就有了解决方案.

You must implement a class to notify prop changed and therefore the prop can not be static. Combine with a singleton pattern and you have yout solution.

public class Global : INotifyPropertyChanged
{
    private string _userName;

    public string UserName
    {
        get
        {
            return this._userName;
        }
        set
        {
            if (this._userName == value)
            {
                return;
            }

            this._userName = value;

            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs("UserName"));
            }
        {
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private Global() {}

    public static readonly Global Get = new Global();
}

用法:

var currUserName = Global.Get.UserName;

Global.Get.PropertyChanged += (s, e) => Console.WriteLine(e.PropertyName);
Global.Get.UserName = "John";

并绑定到 Global.Get 到属性 UserName.

And bind to Global.Get to property UserName.

这篇关于将标签绑定到静态字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆