Bob.
Bob.

Reputation: 4002

Can you call a class' method when you declare the object?

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();

Upvotes: 3

Views: 466

Answers (4)

Trisped
Trisped

Reputation: 6003

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();

Upvotes: 0

zahir
zahir

Reputation: 1432

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.

Upvotes: 0

Joe
Joe

Reputation: 2564

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

Upvotes: 0

user27414
user27414

Reputation:

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()

Upvotes: 4

Related Questions