我正在WPF应用程序中努力通过类似向导的窗口来初始化对象。我有主应用程序窗口,该窗口旨在显示Plan
对象的内容。我想在另一个窗口中初始化Plan
对象,这类似于帮助用户参数化Plan
的向导。
概念如下:
MainWindow.xaml.cs
public partial class MainWindow : RibbonWindow
{
public Plan apActivePlan;
public MainWindow()
{
InitializeComponent();
}
private void rbNewPlan_Click(object sender, RoutedEventArgs e)
{
WndAddEditPlan wndAddPlan = new WndAddEditPlan(ref apActivePlan);
wndAddPlan.ShowDialog();
if (wndAddPlan.DialogResult.HasValue && wndAddPlan.DialogResult.Value)
{
/* "Create" button clicked in wndAddPlan,
* so we update the ListView in MainWindow */
lvPlanRows.ItemsSource = this.apActivePlan.Rows; // this is where the problem occurs - apActivePlan is null despite the fact that it has been initialized by wndAddPlan
}
}
WndAddEditPlan.xaml.cs
public partial class WndAddEditPlan : Window
{
Plan apActivePlan = null;
public WndAddEditPlan(ref Plan apActivePlan)
{
InitializeComponent();
this.apActivePlan = apActivePlan;
if(this.apActivePlan == null)
this.apActivePlan = new Plan();
}
private void btnCreatePlan_Click(object sender, RoutedEventArgs e)
{
DialogResult = true;
}
}
用户单击NewPlan
按钮,并弹出向导以创建新的Plan
。用户填写所需的信息,然后单击CreatePlan
按钮。向导关闭,但是MainWindow中的apActivePlan尚未初始化。
答案 0 :(得分:0)
您不必通过引用类型对象传递
ref
,因为它们 已经是引用Check this
另一件事
this.apActivePlan = new Plan();
在这里,您正在将内存分配给局部变量。
Plan apActivePlan = null;
不是您传入的人
ref Plan apActivePlan
都是不同的内存指针。
因此,您正在将内存分配给WndAddEditPlan的本地引用,并希望初始化MainWindow的变量。
因此更改此行
apActivePlan = new Plan();
代替
this.apActivePlan = new Plan();