开发者

Where to create parametrized ViewModel?

开发者 https://www.devze.com 2023-01-10 06:27 出处:网络
I have recently parametrized my ViewModel\'s contructor. Before that, I was doing this in my window: <Window.DataContext>

I have recently parametrized my ViewModel's contructor. Before that, I was doing this in my window:

<Window.DataContext>
    <vm:MyViewModel />
</Window.DataContext>

The framework instantiated the ViewModel for me.

I know I can set DataContext in code but I would prefer a XAML way so des开发者_C百科igner can display my test data when designing.

Is this possible?


Use an ObjectDataProvider if you want to specify constructor parameters:

<Window.DataContext>
    <ObjectDataProvider ObjectType="vm:MyViewModel"
        xmlns:sys="clr-namespace:System;assembly=mscorlib">
        <ObjectDataProvider.ConstructorParameters>
            <sys:String>A string parameter</sys:String>
            <sys:Int32>42</sys:Int32>
        </ObjectDataProvider.ConstructorParameters>
    </ObjectDataProvider>
</Window.DataContext>


I have no idea how to pass a contructor-parameter, I think it can't be done (but it would be nice if someone proved me wrong).

What you can do is set properties on your ViewModel, as in

<Window.DataContext>
    <vm:MyViewModel  MyProperty="Hello" />
</Window.DataContext>
0

精彩评论

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