Wouterdek/NodeNetwork

Constructor behaviour

hrkrx opened this issue · 2 comments

hrkrx commented

I have a simple application from the getting started tutorial.

It works as expected, but to use it in another application, I tried to adapt it to MVVM, which I was not able to.
I narrowed it down to the InitializeComponent(); method which does some magic I apparently cannot replicate.

Minimum Example:

MainWindow.xaml:

<Window [...]>
  <Grid>
    <nodenetwork:NetworkView x:Name="networkView" />
  </Grid>
</Window>

MainWindow.cs:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        
        // If this line is called after InitializeComponent(); it does not set the ViewModel correctly 
        // networkView = new NetworkView(); 

        var network = new NetworkViewModel();
        networkView.ViewModel = network;
    }
}

I tried to debug this but I got nowhere, calling the constructor of the NetworkView does not seem to create an operational object, how do I create a valid NodeNetwork object without relying on InitializeComponent();?

You should (almost) never have to create a view manually in the C# code.
When the .xaml file is compiled, a second .cs file is auto-generated which includes the InitializeComponent() code. This function instantiates all the views as they are specified in the xaml file. Note that InitializeComponent() does much more than just constructing the object. It also configures its properties, sets up animations, adds it to the visual tree, ... By calling networkView = new NetworkView() manually, you are replacing your local reference to this view, but you have not replaced it everywhere else in the WPF system.

TLDR: Simply remove the line you have commented out. Use the networkView instance that is created by InitializeComponent.

hrkrx commented

Alright