如何从另一个类或窗口访问WPF中的控件 [英] How can I access a control in WPF from another class or window

查看:932
本文介绍了如何从另一个类或窗口访问WPF中的控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在WPF中访问mainWindow中的按钮或文本框之类的控件,但我不能这样做。

I want to access my controls like button or textbox in mainWindow in WPF, but I can't do this.

在Windows窗体应用程序中,它是如此的简单,您可以将该控件的修饰符设置为True,并且可以从该mainWindow的实例访问该控件,但是在WPF中,我无法声明公共控件。我该怎么做?

In Windows Form application it's so easy, you can set modifier of that control to True and you can reach that control from an instance of that mainWindow, but in WPF I can't declare a public control. How can I do this?

推荐答案

要访问其他WPF表单中的控件,您必须将该控件声明为公共控件。 WPF中控件的默认声明是公共的,但是您可以使用以下代码指定它:

To access controls in another WPF forms, you have to declare that control as public. The default declaration for controls in WPF is public, but you can specify it with this code:

<TextBox x:Name="textBox1" x:FieldModifier="public" />

之后,您可以在应用程序的所有活动窗口中搜索以找到具有此类控制功能的窗口:

And after that you can search in all active windows in the application to find windows that have control like this:

foreach (Window window in Application.Current.Windows)
{
    if (window.GetType() == typeof(Window1))
    {
       (window as Window1).textBox1.Text = "I changed it from another window";
    }
}

这篇关于如何从另一个类或窗口访问WPF中的控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆