Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to create parametrized ViewModel?

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 designer can display my test data when designing.

Is this possible?

like image 802
Kugel Avatar asked Aug 03 '10 20:08

Kugel


People also ask

How do I create a ViewModel?

There are three steps to setting up and using a ViewModel: Separate out your data from your UI controller by creating a class that extends ViewModel. Set up communications between your ViewModel and your UI controller. Use your ViewModel in your UI controller.

Is ViewModel part of jetpack?

ViewModel overview Part of Android Jetpack. The ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way. The ViewModel class allows data to survive configuration changes such as screen rotations.

How do you use ViewModelProvider in Kotlin?

Use the 'by viewModels()' Kotlin property delegate or ViewModelProvider , passing in the fragment. This function is deprecated. Use the 'by viewModels()' Kotlin property delegate or ViewModelProvider , passing in the activity. of (fragment: Fragment, factory: ViewModelProvider.


1 Answers

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>
like image 182
Quartermeister Avatar answered Oct 05 '22 01:10

Quartermeister