Providing a custom control with an abstract base class at design time

I am working on a project in which there are several WPF user controls that inherit from an abstract base class (itself based on UserControl). These controls render fine at runtime, but they don't appear in the designer.

I understand that this is because the designer is trying to instantiate the xaml root element, in this case my base class, but he cannot create the instance because it is abstract.

For the record, I know that there are problems such as "templates and methods" with the presence of this type of management hierarchy in WPF, but refactoring the entire project is currently not an option.

My question is this: I know there are design-time attributes for setting DataContext, DesignWidth, etc. I am wondering if you can specify an instance of "development time" or a type that will be presented as a replacement when the control is loaded into the constructor?

+4
source share
1 answer

during development, Visual Studio will attempt to create a new Instant of YourUserControl with a parametric constructor .

if you cannot create usercontrol instantly like this

var myView = new MyUserControl(); //no params 

the constructor will not be able to render.

if the parameter "YourUserControl" requires any parameter. the most popular trick is to create a dedication constructor like this

 public MyUserControl() : this(new MockViewModel(), new MockDataContext){ } // mock Designtime constructor puclic MyUserControl(IViewModel vm, IDataContext context) //runtime constructor { } 

in the MVVM template, some UserControl.DataContext is defined by the user. A type that requires some XAML parameters

 <UserControl.DataContext> <local:MyViewModel /> </UserControl.DataContext> 

You must define a constructor without parameters for the development environment.

  public MyViewModel() : this(new MockEventAggregator()) //for designtime { } [ImportingConstructor] public MyViewModel(IEventAggregator eventAggregator) //for runtime { this._eventAggregator = eventAggregator; //... } 
0
source

Source: https://habr.com/ru/post/1338757/


All Articles