How to access WPF MainWindow Controls from my own .cs file

后端 未结 7 1185
执笔经年
执笔经年 2021-01-31 18:28

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 ano

相关标签:
7条回答
  • 2021-01-31 19:27

    As for why it won't compile, I will assume the compiler error you are getting is...

    An object reference is required for the non-static field, method, or property 'TestApp1.MainWindow.TextBlock1'

    This happens because you are trying to access an TextBlock1 as if it were static. As @JeffRSon stated, create an instance of your MainWindow class first.

    // Create an instance of MainWindow
    var mainWindow = new MainWindow();
    mainWindow.TextBlock1.Text = "Setting Text from My Program";
    

    I assume you may want to display the window as well...

    mainWindow.ShowDialog();
    
    0 讨论(0)
提交回复
热议问题