c# - 如何从我自己的 .cs 文件访问 WPF MainWindow 控件

标签 c# wpf controls

我是一名新手,正在努力完成看似非常简单的任务。如何从另一个 cs 文件修改 MainWindow TextBlock 的属性。精确的代码解决方案将非常有帮助。

下面是精简代码。我使用静态类会导致额外的问题吗?

在文件中: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

namespace TestApp1  
{  
public partial class MainWindow : Window  
    {  
        public MainWindow()  
        {  
            InitializeComponent();  
            TextBlock1.Text = "Setting Text from MainWindow";  
            MyProgram.myProgramStart();  
        }  
    }  
}  

在文件中: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。然而,有时您需要按照您的要求进行操作,因此您需要的代码是:

((MainWindow)System.Windows.Application.Current.MainWindow).TextBlock1.Text = "Setting Text from My Program";

关于c# - 如何从我自己的 .cs 文件访问 WPF MainWindow 控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17001486/

相关文章:

c# - 为什么 TextureCoordinates 对于 Viewport2DVisual3D 按预期工作,但对于 GeometryModel3D 却不行?

wpf - 带图像的按钮,为什么单击图像时按钮命令不触发?

WPF - 让 ViewModel 与 WPF 无关是一个好主意吗?

.net - SuspendLayout 和 BeginUpdate 的区别

C# 锁定 WinForm 控件

c# - OleDbAdapter 读取列数据

c# - 数据绑定(bind) : does not contain a property with the name 'CategoryId' error

c# - 如何将密码StandardInput传递给pg_dump?

java - Java声音:集合控件的持久性是什么?

c# - 带有参数的 Blazor 服务器页面在手动刷新时抛出 "404 not found "