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

后端 未结 4 870
感情败类
感情败类 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:31

    Application.Current contains a collection of all windows in you application, you can get the other window with a query such as

    var window2 = Application.Current.Windows
        .Cast<Window>()
        .FirstOrDefault(window => window is Window2) as Window2;
    

    and then you can reference the control from your code, as in

    var richText = window2.MyRichTextBox
    
    0 讨论(0)
  • 2020-12-09 13:40

    You cant access the texbox from another window as it is private to that window you can however work around this by exposing the RichTextBox as a public property on your window (hack)

    public RichTextBox RichTextBox {
      get{
        //the RichTextBox would have a property x:Name="richTextbox" in the xaml
        return richTextBox;
      }
    }
    
    0 讨论(0)
  • 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:

    <RichTextBox x:Name="richtextbox" ... />
    

    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);
    
    0 讨论(0)
  • 2020-12-09 13:44
    Application.Current.Windows.OfType(Of MainWindow).First
    
    0 讨论(0)
提交回复
热议问题