开发者

Rendering User Control with Abstract Base class in Design Time

开发者 https://www.devze.com 2023-02-08 21:17 出处:网络
I\'m working on a project that has several WPF User Controls that inherit from an abstract base class (itself based on UserControl).These controls render just fine at runtime, but they don\'t render i

I'm working on a project that has several WPF User Controls that inherit from an abstract base class (itself based on UserControl). These controls render just fine at runtime, but they don't render in the designer.

I gather that this happens because the designer attempts to create an instance of the xaml root element, i开发者_StackOverflow社区n this case my base class, but it can't create an instance because it is abstract.

For the record, I know that there are "patterns & practices" type issues with having this type of control hierarchy in WPF, but refactoring the entire project is not an option currently.

My question is this: I know that there are design time attributes for setting the DataContext, DesignWidth, etc. What I'm wondering is, can you give a "design time" instance or type to be provided as a replacement when the control is loaded in the designer?


in design time Visual Studio will try to create new Instant of YourUserControl with parameterless constructor.

if you can't create usercontrol instant like this

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

the designer will fail to render.

if YourUserControl required any parameter. the most popular trick is to create dedicate constructor like this

public MyUserControl() : 
   this(new MockViewModel(), new MockDataContext){ } // mock Designtime constructor

puclic MyUserControl(IViewModel vm, IDataContext context) //runtime constructor
{ 
}

in MVVM pattern some UserControl.DataContext is user-defined Type that required some params XAML

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

You must define parameterless constructor for design-time environment.

    public MyViewModel() : this(new MockEventAggregator()) //for designtime
    { }

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

精彩评论

暂无评论...
验证码 换一张
取 消