【问题标题】:Using a class initiated in one method in another method在另一种方法中使用在一种方法中启动的类
【发布时间】:2011-02-21 22:21:17
【问题描述】:

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

【问题讨论】:

    标签: c# wpf datagrid methods


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      假设您没有在 FromFile_Click 中调用 otherMethod,您需要将其设为实例变量 - 就像您的 TabControl 一样,但希望不公开。我假设otherMethod 实际上是为了处理某种事件,而不是被直接调用。

      现在假设您希望每个MainWindow 实例都有一个DataGrid,与该窗口相关联。如果不是这种情况,您需要提供更多信息。

      【讨论】:

      • 'otherMethod' 是为了处理一个事件,我还没有定义某种按钮点击。看,我不能将“TabItem”或“datagrid”设为实例变量,因为我不知道用户打开了多少文件。
      • @anon:所以如果可以打开两个数据网格,您希望otherMethod 引用哪一个?如果你能解决那个,剩下的就很清楚了。
      • 我要做的是,当用户单击按钮时,将选项卡更改为平铺视图。示例:假设打开了几个选项卡,每个选项卡都有一个带有独立数据的数据网格。如果用户单击一个按钮,则每个数据网格将移动到一个单独的图块(因此,作为选项卡子项的数据网格将变为图块的子项)。 tc 将被隐藏,tv(定义如下)将变得可见。相反的情况也可能发生。 private TileViewControl tv = new TileViewControl(); 添加在定义 tc 的下方。所以我猜,otherMethod 将引用所有数据网格。
      • 正确 - 所以如果它要引用 all 数据网格,只需使用 List<DataGrid> 变量即可。
      【解决方案3】:

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

      这样,当您分配“dg”时,它可以通过任何其他方法工作(几乎没有限制)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-10
        • 1970-01-01
        • 1970-01-01
        • 2013-02-10
        • 1970-01-01
        • 2011-07-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多