简体   繁体   English

如何从wpf中的另一个窗口访问一个窗口的控件(richtextbox)?

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

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. 我在这里和msdn上搜索过,但一直无法找到答案。 I need to be able to set the richtextboxes selection via richtextbox.Selection.Select(TextPointer1, Textpointer2). 我需要能够通过richtextbox.Selection.Select(TextPointer1,Textpointer2)设置richtextboxes选择。

Application.Current contains a collection of all windows in you application, you can get the other window with a query such as Application.Current包含您应用程序中所有窗口的集合,您可以通过查询获取其他窗口

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) 您无法从另一个窗口访问texbox,因为它是该窗口的私有,但您可以通过将RichTextBox作为窗口上的公共属性公开来解决此问题(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. 你应该可以从后面的Window2代码访问Window1上的控件,如果这是你想要的。 Generated fields are internal by default . 生成的字段默认内部字段。

All you need is to name the control on Window1 , like this: 您只需要在Window1上命名控件,如下所示:

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

In Window2 code behind: Window2代码后面:

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. 更好的选择是将选择操作封装在Window1后面的代码中的方法中,以避免泄露内部。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM