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

后端 未结 7 1187
执笔经年
执笔经年 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:07

    Basically there are more than 2-3 methods. Given method is quite easier to understand & handle. You can access MainWindow controls by following codes (1),(2),(3),(4).

    In File: MainWindow.xaml.cs

      public partial class MainWindow
      {
       internal static MainWindow Main; //(1) Declare object as static
       public MainWindow()
        {
            InitializeComponent();
        }
    
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
           Main =this; //(2) Defined Main (IMP)
          var AnyClassORWindow=new Class1(); //Initialize another Class
          AnyClassORWindow.ShowValue();
        }
      }
    

    In File: Class1.cs

      internal class Class1 : MainWindow //(3) Inherited
        {
          internal void Display()
            {
               MessageBox.Show(Main.TextBox1.Text); //(4) Access MainWindow Controls by adding 'Main' before it.
             }
         }
    

    Notes:-

    1. It's good practice to use code (2) after window LOADED not in CONSTRUCTOR.
    2. Code (2) in constructor may leave run-time problems.
    3. Another simple method is to use 'ref MainWindow_field' by passing to each class's Constructor OR assign '(MainWindow) Application.Current.MainWindow' to static Main.

提交回复
热议问题