2010-05-20 99 views
2

我有一个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的父项?

回答

4

假设你不打电话内的otherMethod,你需要使它成为一个实例变量 - 就像你的TabControl是,除了希望不公开。我假设otherMethod实际上是为了处理某种事件,而不是直接调用。

现在假设您想每个MainWindow的实例有一个DataGrid与该窗口关联。如果情况并非如此,则需要提供更多信息。

+0

“otherMethod”是为了处理事件的方式,某种按钮的点击我还没有定义。请参阅我无法将'TabItem'或'datagrid'作为实例变量,因为我不知道用户打开了多少个文件。 – anon 2010-05-20 15:15:10

+0

@anon:因此,如果可以打开两个数据网格,您希望'otherMethod'引用哪一个?如果你可以工作*,那么其余的可能会很清楚。 – 2010-05-20 15:22:16

+0

我想要做的是,当用户单击按钮时,将选项卡更改为平铺视图。示例:假设有多个选项卡打开,每个选项卡都有一个具有独立数据的数据网格。如果用户点击一个按钮,那么每个数据网格将移动到一个单独的图块(因此,作为选项卡的子节点的数据网格将更改为图块的子节点)。 'tc'将被隐藏,并且'tv'(定义如下)将变为可见。相反的情况也可能发生。 '私人TileViewControl tv = new TileViewControl();'在下面添加'tc'的地方被添加。 所以我想'otherMethod'会引用所有的数据网格。 – anon 2010-05-20 15:37:14

0

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

0

将DataGrid dg设置为属性,而不是在FromFile_click中声明。

此当你将“危险品”,它将从任何其他方法的工作(数限制)

相关问题