将文本框文本绑定到静态属性 [英] Bind Textbox Text to a Static Property

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

问题描述

我有一个具有以下静态属性的静态类:

I have a Static Class with the following Static Property:

 public static class PrintingMethods
{
 public static String DocsCountString
    {
        get
        {
            return printDocuments.Count.ToString();
        }
    }}

我有一个绑定到此属性的文本框:

I have a text box that I bind to this property:

<TextBlock Text="{x:Static  my:PrintingMethods.DocsCountString}" x:Name="PagesNumber"/>

这有效-我可以在文本中看到数字,但是如果属性值更改,它永远不会更改.

This works - I can see the number in the Text, But it never changes If the Property Value Change.

我对此很陌生,我知道有一些东西,例如Dependency Object和INotify Interface,但这不适用于Static.

I am quite new to this, I know there are things like Dependency Object and INotify Interface but this won't work for Static.

如果任何人都可以通过工作代码(对我编写的内容进行修改)来帮助我,以实现实时的文本更改,那就太好了,谢谢!

If anyone can help me with a working code (modification to what I wrote) to Achieve real time textChange that would be great, Thanks!!!

推荐答案

回答我们的评论: 如果您使用单例模式,可以像这样绑定它

Answer on our comments: If you use the Singleton Pattern, you can bind to it like that

public sealed class MySingleton : INotifyPropertyChanged
{
    public void RaiseProperty(string aPropName)
    {
        // implementation of INotifyPropertyChanged
    }

    public static MySingleton Instance 
    { 
        get{ return sInstance; } 
    }

    public string MyProperty
    {
        get {return mMyProperty;}
        set {mMyProperty = value; RaiseProperty("MyProperty"); }
    }

    private string mMyProperty;
    private static MySingleton sInstance = new MySingleton();
}

如您所见,您可以轻松地将INotifyPropertyChanged接口和实现与单例类一起使用.您可能想将构造函数设为私有,以禁止创建此类的另一个实例.也可以延迟分配MySingleton实例.您将在stackoverflow上找到有关单例的更多信息.

As you can see you can easily use the INotifyPropertyChanged interface and implementation with a singleton class. You might want to make the constructor private to disallow creating another instance of this class. Also it would be possible to lazy allocate the MySingleton instance. You will find much more about singletons on stackoverflow.

<TextBlock Text="{Binding Source={x:Static  my:MySingleton.Instance}, Path=MyProperty}"/>

现在这里的重要部分是绑定和覆盖的Source.通常,绑定采用当前的DataContext.通过设置新的SourceDataContext是不相关的,并且新的Source用于获取Path属性后面的值.

The important part here now is the Binding and the overriden Source. Usually Binding takes the current DataContext. By setting a new Source the DataContext is irrelevant and the new Source is used to get the value behind the Path property.

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

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