C# 如何从另一个类或窗口访问 WPF 中的控件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13644114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I access a control in WPF from another class or window
提问by Ahad aghapour
I want to access my controls like button or textbox in mainWindow in WPF, but I can't do this.
我想在 WPF 的 mainWindow 中访问我的控件,如按钮或文本框,但我不能这样做。
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?
在 Windows 窗体应用程序中,这非常简单,您可以将该控件的修饰符设置为 True,并且您可以从该 mainWindow 的实例访问该控件,但在 WPF 中我无法声明公共控件。我怎样才能做到这一点?
采纳答案by Ahad aghapour
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:
要访问其他 WPF 表单中的控件,您必须将该控件声明为公共控件。WPF 中控件的默认声明是公开的,但您可以使用以下代码指定它:
<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";
}
}
回答by BlokeTech
Just declare your control like this to make it public:
只需像这样声明您的控件以使其公开:
<TextBox x:Name="textBox1" x:FieldModifier="public" />
You can then access it from another control.
然后您可以从另一个控件访问它。
回答by eMi
Unfortunately, the basics of WPF are data bindings. Doing it any other way is 'going against the grain', is bad practice, and is generally orders of magnitude more complex to code and to understand.
不幸的是,WPF 的基础是数据绑定。以任何其他方式进行操作都是“违背常规”,是不好的做法,并且通常编码和理解要复杂几个数量级。
To your issue at hand, if you have data to share between views (and even if it's only one view), create a view model class which contains properties to represent the data, and bind to the properties from your view(s).
对于您手头的问题,如果您有数据要在视图之间共享(即使它只有一个视图),请创建一个视图模型类,其中包含表示数据的属性,并绑定到您的视图中的属性。
In your code, only manage your view model class, and don't touch the actual view with its visual controls and visual composition.
在你的代码中,只管理你的视图模型类,不要用它的视觉控件和视觉组合来接触实际的视图。
回答by Jean
I was also struggling with this when I started WPF. However, I found a nice way around it similar to the good old fashioned win forms approach (coding VB.NET, sorry). Adding on what was said earlier:
当我开始 WPF 时,我也在为此苦苦挣扎。但是,我找到了一个很好的方法来解决它,类似于老式的 win 表单方法(编码 VB.NET,抱歉)。补充一下之前说的:
To directly change properties of objects from a module or a different class for an active window:
要直接更改活动窗口的模块或不同类中对象的属性:
Public Class Whatever
Public Sub ChangeObjProperties()
' Here the window is indexed in case of multiple instances of the same
' window could possibly be open at any given time.. otherwise just use 0
Dim w As MainWindow = Application.Current.Windows(0)
w.Button1.Content = "Anything"
End Sub
End Class
You obviously have to instantiate Whateverbefore ChangeObjProperties()can be called in your code.
您显然必须先实例化,Whatever然后ChangeObjProperties()才能在您的代码中调用。
Also there is no need to worry about naming in XAML regarding object accessibility.
此外,无需担心 XAML 中关于对象可访问性的命名。
回答by Rafael Ventura
I found that in WPF, you have to cast Window as a MainWindow.
我发现在 WPF 中,您必须将 Window 转换为 MainWindow。
Looks complicated but it's very easy!However, maybe not best practices.
看起来很复杂,其实很简单!但是,可能不是最佳实践。
Supposing we have a Label1, a Button1 in the MainWindow, and you have a class that deals with anything related to the User Interface called UI.
假设我们在 MainWindow 中有一个 Label1、一个 Button1,并且您有一个类来处理与称为 UI 的用户界面相关的任何事情。
We can have the following:
我们可以有以下几点:
MainWindow Class:
主窗口类:
namespace WpfApplication1
{
public partial class MainWindow : Window
{
UI ui = null;
//Here, "null" prevents an automatic instantiation of the class,
//which may raise a Stack Overflow Exception or not.
//If you're creating controls such as TextBoxes, Labels, Buttons...
public MainWindow()
{
InitializeComponent(); //This starts all controls created with the XAML Designer.
ui = new UI(); //Now we can safely create an instantiation of our UI class.
ui.Start();
}
}
}
UI Class:
界面类:
namespace WpfApplication1
{
public class UI
{
MainWindow Form = Application.Current.Windows[0] as MainWindow;
//Bear in mind the array! Ensure it's the correct Window you're trying to catch.
public void Start()
{
Form.Label1.Content = "Yay! You made it!";
Form.Top = 0;
Form.Button1.Width = 50;
//Et voilá! You have now access to the MainWindow and all it's controls
//from a separate class/file!
CreateLabel(text, count); //Creating a control to be added to "Form".
}
private void CreateLabel(string Text, int Count)
{
Label aLabel = new Label();
aLabel.Name = Text.Replace(" ", "") + "Label";
aLabel.Content = Text + ": ";
aLabel.HorizontalAlignment = HorizontalAlignment.Right;
aLabel.VerticalAlignment = VerticalAlignment.Center;
aLabel.Margin = new Thickness(0);
aLabel.FontFamily = Form.DIN;
aLabel.FontSize = 29.333;
Grid.SetRow(aLabel, Count);
Grid.SetColumn(aLabel, 0);
Form.MainGrid.Children.Add(aLabel); //Haha! We're adding it to a Grid in "Form"!
}
}
}
回答by Morten Finnerud
The default declaration of controls is non public, internal and not public!
控件的默认声明是非公开的、内部的而不是公开的!
Access of the controls from within the same assembly is hence allowed. If you want to access a control on a wpf form from another assembly you have to use the modifier attribute x:FieldModifier="public" or use the method proposed by Jean.
因此允许从同一程序集中访问控件。如果要从另一个程序集中访问 wpf 表单上的控件,则必须使用修饰符属性 x:FieldModifier="public" 或使用 Jean 提出的方法。
回答by Just Fair
var targetWindow = Application.Current.Windows.Cast<Window>().FirstOrDefault(window => window is principal) as principal;
targetWindow .BssAcesso.Background = Brushes.Transparent;
just call any control of it from your current window:
只需从当前窗口调用它的任何控件:
targetWindow.ABUTTON.Background = Brushes.Transparent;
How can I access one window's control (richtextbox) from another window in wpf?
回答by Hashim Shubber
To access any control in another window is so simple. Lets say to access from a Login window to MainWindow. Here is the steps:
在另一个窗口中访问任何控件是如此简单。假设从登录窗口访问 MainWindow。以下是步骤:
MainWindow MW = new MainWindow(); //declare the mainwindow
MW.Label1.Content = "Hello world"; //specify what control
MW.ShowDialog(); //check what happen to that control
Good programming
良好的编程

