我对c#很新,对wpf很新,所以如果这是一个非常愚蠢的问题,请原谅我....
我有三节课。这是我的程序的结构。
在MainWindow类中,应该完成一些初始化步骤,其中之一是使用另一个类中的方法创建数据表:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
savelabels table = new savelabels();
table.createlabeltable();
//...some other stuff that works
}
}
这里应该创建,填充和按需创建数据表的类返回:
public class savelabels
{
DataTable labelcoords = new DataTable();
public void createlabeltable()
{
DataColumn column;
column = new DataColumn();
column.DataType = System.Type.GetType("System.Double");
column.ColumnName = "id";
labelcoords.Columns.Add(column);
}
public void saveposition(double x)
{
DataRow row = labelcoords.NewRow();
row["id"] = x;
labelcoords.Rows.Add(row);
}
public DataTable GetDataTable()
{
return labelcoords;
}
}
然后我有第三个类,其中有一个方法应该填充数据表:
public class getdata
{
public void filltable()
{
double x = 123;
savelabels ctable = new savelabels();
ctable.saveposition(x);
}
}
我想通过getdata类中的其他方法使用saveposition方法写入表中的值。问题是即使saveposition(x)方法也没有工作,因为没有" id" labelcoords表中的列,所以我想saveposition方法无法访问MainWindow类中创建的表。
答案 0 :(得分:0)
如果您想要从另一个类实例访问类实例,则需要将实例传递给它。我没有看到你创建getdata
的实例,所以我无法重构任何实例。但是,它会像YourgetdataInstance.filltable(savelabels mytable)
那样,在其中,您将删除新实例的实例化,只使用mytable.saveposition(x)
。由于方法明确需要一定的结构,我倾向于选择评论中提出的simon。
但是,如果您想将filltable
保留在单独的类中,可以提供我所展示的参数。如果您不需要getdata
的实际实例,则可以将其更改为static
类,以便直接调用它。