简体   繁体   中英

Using a class initiated in one method in another method

I have a C# WPF app that every time the user opens a new file, the contents are displayed in a datagrid.

public partial class MainWindow : Window
{
     public TabControl tc = new TabControl();

     public MainWindow()
     {
         InitializeComponents();
     }

     private FromFile_click(object sender, RoutedEventArgs e)
     {
         //gets information from file and then...

         if (numberOfFiles == 0)
         {
             masterGrid.Children.Add(tc);
         }
         TabItem ti = new TabItem();
         tc.Items.Add(ti);

         DataGrid dg = new DataGrid();
         ti.Content = dg;

         dg.Name = "Grid"+ ++numberOfFiles;

         dg.ItemSource = data;
     }

     private otherMethod(object sender, RoutedEventArgs e)
     {

     }
}

My question is, how do I use the data in dg in the method "otherMethod"? Also, is it possible to change the parent of dg from the method "otherMethod"?

Assuming you're not calling otherMethod within FromFile_Click , you need to make it an instance variable - like your TabControl is, except hopefully not public. I'm assuming otherMethod is actually meant to handle an event of some kind, rather than being called directly.

Now this is assuming that you want one DataGrid per instance of MainWindow , associated with that window. If that's not the case, you'd need to provide more information.

您必须将其作为参数传递给其他方法otherMethod或使其成为成员变量。

set the DataGrid dg as a property instead of declaring inside the FromFile_click.

This way when you assign "dg" it will work from any other method (few restrictions apply)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM