How can I access one window's control (richtextbox) from another window in wpf?

后端 未结 4 883
感情败类
感情败类 2020-12-09 12:53

I\'m sure this is something very simple but I can\'t figure it out. I\'ve searched here and on msdn and have been unable to find the answer. I need to be able to set the ric

4条回答
  •  难免孤独
    2020-12-09 13:43

    You should be able to access controls on Window1 from Window2 code behind, if that's what you want. Generated fields are internal by default.

    All you need is to name the control on Window1, like this:

    
    

    In Window2 code behind:

    var window = new Window1(); // or use the existing instance of Window1
    window.richtextbox.Selection.Select(TextPointer1, Textpointer2);
    

    A better option would be to encapsulate select operation in a method in code behind of Window1, to avoid giving away internal. Then you would have:

    // Window1.cs
    public void Select(int param1, int param2)
    {
        richtextbox.Selection.Select(param1, param2);
    }
    
    // Window2.cs
    var window = new Window1(); // or use the existing instance of Window1
    window.Select(TextPointer1, Textpointer2);
    

提交回复
热议问题