Bind Textbox Text to a Static Property

有些话、适合烂在心里 提交于 2019-12-12 03:22:36

问题


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.

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!!!


回答1:


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

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}"/>

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.




回答2:


you should use function in modifier is internal like:

Form2:

internal string foo()
{
    return nom;
}

Form1:

form2 win= new form2();
win.ShowDialog();
Textbox.Text = win.foo();


来源:https://stackoverflow.com/questions/9564694/bind-textbox-text-to-a-static-property

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!