在一种方法中使用在另一种方法中启动的类
我有一个 C# WPF 应用程序,每次用户打开新文件时,内容都会显示在数据网格中。
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)
{
}
}
我的问题是,如何在方法“otherMethod”中使用 dg 中的数据?另外,是否可以从方法“otherMethod”更改 dg 的父级?
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"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设您没有在
FromFile_Click
中调用otherMethod
,则需要将其设为实例变量 - 就像您的TabControl
一样,但希望不是公开的。我假设 otherMethod 实际上是为了处理某种事件,而不是直接调用。现在假设您希望每个
MainWindow
实例有一个与该窗口关联的DataGrid
。如果情况并非如此,您需要提供更多信息。Assuming you're not calling
otherMethod
withinFromFile_Click
, you need to make it an instance variable - like yourTabControl
is, except hopefully not public. I'm assumingotherMethod
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 ofMainWindow
, associated with that window. If that's not the case, you'd need to provide more information.您必须将其作为参数传递给其他方法
otherMethod
或使其成为成员变量。You have to pass it as a parameter to the other method
otherMethod
or make it a member variable.将 DataGrid dg 设置为属性,而不是在 FromFile_click 内声明。
这样,当您分配“dg”时,它可以通过任何其他方法工作(几乎没有限制)
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)