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

♀尐吖头ヾ 提交于 2019-11-28 09:27:11
Ian Oakes

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
Application.Current.Windows.OfType(Of MainWindow).First

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

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