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?
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With