3

I have a class, where I declare it, but that class gets added as an item to another bigger class. Is there a way to call the Init() method in the same statement as the call? Similar to defining public properties/variables when you call the constructor. I don't want to call the Init() method in the constructor because it messes with the WPF Designer.

 FitsView fv = new FitsView();
 fv.Init();
Bob.
  • 3,894
  • 4
  • 44
  • 76

4 Answers4

4

You could use a static function to do that:

public static FitsView CreateFitsView()
{
    var fv = new FitsView();
    fv.Init();
    return fv;
}

Then you simply call that static function instead of new FitsView()

Jon B
  • 51,025
  • 31
  • 133
  • 161
0

You could also try hooking a custom event to your FitsView if it knows when it's ready to be initialized?

And use it like this:

FitsView fv = new FitsView();
fv.someCustomEvent += (o,e) => { fv.Init(); };
Joe
  • 2,496
  • 1
  • 22
  • 30
0

Similar to the StringBuilder.Append you could alter Init to return a reference to the object.

Public FitsView Init()
{
    //Do stuff

    return this;
}

Then:

FitsView fv = new FitsView().Init();
Trisped
  • 5,705
  • 2
  • 45
  • 58
0

If the designer gets problematic because of your init method there are two reasons I can think of:

  • It is because something you do in Init method needs locality of your application (reading resources or files or using hardware)
  • Calling your Init method needs some external assemblies to be loaded dynamically.

For the first matter you may want to check:

  1. For your class: Is there a DesignMode property in WPF?
  2. For your view model: http://blog.laranjee.com/how-to-get-design-mode-property-in-wpf/

Also people in here pointed out this bug so please beware (hosting wpf in winforms): https://connect.microsoft.com/VisualStudio/feedback/details/620001/system-componentmodel-designerproperties-getisindesignmode-does-not-work-if-the-wpf-is-hosted-on-a-winform#tabs

For the second matter you can wrap your Init method in another let's say InitWrapper and do your design mode check for wrapper method.

Community
  • 1
  • 1
zahir
  • 1,298
  • 2
  • 15
  • 35