0

I'm struggling in WPF application to initialize object with help of a wizard-like window. I've got main application window which is meant to show the contents of a Plan object. I want to initialize the Plan object in another window which is something like a wizard to help user parametrize Plan.

The concept is following:

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;
    }
}

The user clicks on NewPlan button and wizard pops up to create new Plan. The user fills up required information and clicks on CreatePlan button. The wizard closes but the apActivePlan within MainWindow is not being initialized.

1 Answers1

0

You don't have to pass ref with reference type objects because of they are already references Check this

Another thing

this.apActivePlan = new Plan();

Here you are assigning memory to a local variable.

Plan apActivePlan = null;

Not the one you passed in

ref Plan apActivePlan

both are different memory pointers.

so you are the assigning memory to local reference to WndAddEditPlan and expecting variable of MainWindow to be initialized.

So change this line

apActivePlan = new Plan();

instead of

this.apActivePlan = new Plan();
Mihir Dave
  • 3,954
  • 1
  • 12
  • 28
  • I have removed the `ref` keyword and adjusted the line to `apActivePlan = new Plan();` but still after returning to MainWindow the apActivePlan member within MainWindow is `null`. – Krzysztof Jakóbczyk Jul 09 '18 at 12:26
  • If, instead of `WndAddEditPlan wndAddPlan = new WndAddEditPlan(ref apActivePlan);`, I define a constructor in WndAddEditPlan to receive reference to MainWindow instead of only the apActivePlan field it starts to work. Maybe there's something with `DataContext` messed up? – Krzysztof Jakóbczyk Jul 09 '18 at 12:48