如何从另一个类或窗口访问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";
}
}