如何从我自己的.cs文件访问WPF MainWindow控件 [英] How to access WPF MainWindow Controls from my own .cs file
问题描述
我是NOVICE,并且在看来应该是一件非常简单的任务上非常挣扎。如何从另一个CS文件修改 MainWindow
TextBlock
的属性。精确的代码解决方案将非常有帮助。
I am a NOVICE and am very much struggling with what seems should be a very simple task. How do I modify a property of a MainWindow
TextBlock
, from another cs file. An exact code solution would be extremely helpful.
下面是精简的代码。我对静态类的使用会给我带来额外的问题吗?
Below is the stripped down code. Is my use of static class causing me extra issues?
在文件中:MainWindow.xaml
In File: MainWindow.xaml
<Window x:Class="TestApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBlock x:Name="TextBlock1" HorizontalAlignment="Left" Margin="107,71,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top"/>
</Grid>
</Window>
文件内:MainWindow.xaml.cs
In File: MainWindow.xaml.cs
namespace TestApp1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
TextBlock1.Text = "Setting Text from MainWindow";
MyProgram.myProgramStart();
}
}
}
在文件中:CodeFile1.cs
In File: CodeFile1.cs
namespace TestApp1
{
public static class MyProgram
{
public static void myProgramStart()
{
// ... blah blah blah
// I want to do something like follows, but won't compile
MainWindow.TextBlock1.Text = "Setting Text from My Program";
}
}
}
推荐答案
因为没有人真正回答过这个问题,所以我将告诉您如何实现您想要的目标,但是请听听那些在实际应用程序中将使用MVVM的发帖人。但是有时您需要做的事情就是这样,您需要的代码是:
Because nobody else has actually answered the question I'm going to tell you how to achieve what you want, but do listen to the posters who said that in a real application you would use MVVM. However there are times when you need to do what you ask so the code you need is:
((MainWindow)System.Windows.Application.Current.MainWindow).TextBlock1.Text = "Setting Text from My Program";
这篇关于如何从我自己的.cs文件访问WPF MainWindow控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!