从单独文件中的类访问MainWIndow控件 [英] Access MainWIndow Control from a class in a separate file
问题描述
我在XAML的MainWindow中添加了 TextBlock
。我需要在驻留在单独的.cs文件中的单独类中更改TextBlock Text。我尝试了以下操作:
I add a TextBlock
to the MainWindow in XAML. And I would need to change the TextBlock Text in a separate class resided in a separate .cs file. I tried the following:
private static fooNameSpace.MainWindow tW1;
tW1 = this;
tW1.textBlock1.Text = "This is a paragraph";
如果该类与MainWindow类位于同一文件中,则该方法有效。如果类位于单独的文件中,则返回null。我已经使用fooNameSpace添加了;
仍然不起作用
It worked if the class is reside in the same file as the MainWindow class, But it throws me an null exception if the class is reside in a separate file. I have already added the using fooNameSpace;
Still doesn't work
我找不到正确的方法从一个单独的文件类到MainWindow及其控件进行引用。提示任何人?
谢谢,
I can't figure out the right way to make a reference from a separate file class to the MainWindow and it's Control. Tips anyone? thanks,
推荐答案
要回答我的问题-使用内部
而不是 public
。
To answer my question - use internal
instead of public
.
// in MainWindow.xaml.cs internal
internal static fooNameSpace.MainWindow tW1;
// in foo.cs
MainWindow.tW1.txtBlock1.Text = "This is a paragraph";
内部关键字允许其他CS文件中的其他类进行访问到MainWindow控件。
但是我不太确定要使用Internal来解决此问题,因为它允许我的其他班级访问MainWindow中的所有其他内容……还有更好的选择吗?
the internal keyword allows other class in other cs file to get access to MainWindow controls. But I'm not so sure about using internal to solve this problem as it allow my other class to get access to everything else in my MainWindow...any better option out there?
这篇关于从单独文件中的类访问MainWIndow控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!