如何调用DataGrid"选择的项目"来自另一个班级?

时间:2014-09-19 00:47:06

标签: c# wpf datagrid wpfdatagrid

下面我有一个从数据库中删除记录的方法。它在同一个对话框中工作得很好。问题是我希望在另一个窗口,一个表单对话框而不是DataGrid上使用此方法。一旦我移动它,它就不再有用了。

    public partial class ProjectsTable : Window
{
    public ProjectsTable()
    {
        InitializeComponent();
    }

    //populates a DataGrid called "ProjectData" on the "ProjectsTable.xaml"
    private void Window_Loaded(Object sender, RoutedEventArgs e)
    {
        BillableProjectsDataContext project = new BillableProjectsDataContext();
        List<Project> projects = (from p in project.Projects
                                  select p).ToList();
        ProjectData.ItemsSource = projects;
    }

    // deletes the selected project
    private void btnDeleteProject_Click(object sender, RoutedEventArgs e)
    {
        //this is the most important part, it tells the method which record to delete
        Project selected = ProjectData.SelectedItem as Project;
        //calls another class called "Menu_SQL" and uses it's DeleteProject method
        Menu_SQL.DeleteProject(selected);
        Window_Loaded(null, null);
    }
}

上面的方法工作正常,问题是我希望在我的表单上有这个方法,这是另一个窗口 一旦我移动它,它就不再有用了。

具体错误是“名称'ProjectData'在当前上下文中不存在”。

但确实存在,它是DataGrid的名称。

public partial class DataForm : Window
{
    public Project project;
    public DataForm(Project project)
    {
        InitializeComponent();
        this.project = project;
    }
    public DataForm()
    {
        InitializeComponent();
    }

    // deletes the selected project, the same exact method as before, just in another window
    private void btnDeleteProject_Click(object sender, RoutedEventArgs e)
    {
        //this is the most important part, it tells the method which record to delete
        // the problem is that this line will error because "The name 'ProjectData' does not exist in the current context"
        Project selected = ProjectData.SelectedItem as Project;
        Menu_SQL.DeleteProject(selected);
    }
}

1 个答案:

答案 0 :(得分:0)

也许您可以在DataForm中添加属性,如

public DataGrid ProjectData { set; get; }

您可以在DataForm show之前设置它。