从单独文件中的类访问 MainWIndow 控件
我将 TextBlock
添加到 XAML 中的 MainWindow。我需要更改位于单独 .cs 文件中的单独类中的 TextBlock 文本。我尝试了以下操作:
private static fooNameSpace.MainWindow tW1;
tW1 = this;
tW1.textBlock1.Text = "This is a paragraph";
如果该类与 MainWindow 类驻留在同一文件中,它会起作用,但如果该类驻留在单独的文件中,它会引发空异常。我已经添加了 using fooNameSpace;
仍然不起作用
我无法找出从单独的文件类到 MainWindow 及其 Control 的引用的正确方法。有人提示吗? 谢谢,
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";
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
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,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要回答我的问题 - 使用
internal
而不是public
。Internal 关键字允许其他 cs 文件中的其他类访问 MainWindow 控件。
但我不太确定使用内部来解决这个问题,因为它允许我的其他类访问我的主窗口中的其他所有内容......还有更好的选择吗?
To answer my question - use
internal
instead ofpublic
.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?
您提到了 XAML,因此我假设您正在谈论 WPF 应用程序。 .xaml 和 .xaml.cs 文件齐头并进。如果您需要访问该“控件”中的任何内容,您将需要实例化它或需要在外部类中引用它。
至于错误,您声明了 tw1 但它没有实例化 - 这就是您收到 Null 异常错误的原因。执行
tw1 = this
也是行不通的。You mentioned XAML, so I will assume you are talking about a WPF application. the .xaml and .xaml.cs files go hand in hand. If you need to access anything in that "control" you will need to instantiate it or need its reference in the outside class.
As for the error, you declare the
tw1
but it is not instantiated - which is the reason you are getting a Null exception error. Doingtw1 = this
is also won't work.