Access MainWIndow Control from a class in a separate file

前端 未结 2 1350
无人共我
无人共我 2021-01-22 16:01

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

相关标签:
2条回答
  • 2021-01-22 16:43

    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";
    

    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?

    0 讨论(0)
  • 2021-01-22 16:59

    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. Doing tw1 = this is also won't work.

    0 讨论(0)
提交回复
热议问题