The DataTemplate in Resource sets the ViewModel to view, but then

I am trying to understand many different ways to set the datacontext view in the viewmodel.

One of them at this moment looks something like this:

I have a MainWindowResource file:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:vw="clr-namespace:DemoStuffPartII.View" xmlns:vm="clr-namespace:DemoStuffPartII.ViewModel"> <DataTemplate DataType="{x:Type vm:PersonViewModel}"> <vw:PersonView /> </DataTemplate> 

But it’s also immediately where I hide. I know that I should use ContentControl in the view. But what is the best way to customize? How to do it?

+4
source share
3 answers

So you can enable ViewSwitching navigation in your MVVM application.

Other missing bits: in view β†’

 <ContentControl Content="{Binding CurrentPage}" /> 

in ViewModel -> (pseudo-code)

 Prop ViewModelBase CurrentPage. 

Note that if all you need is to connect the ViewModel to the view, you can simply completely delete all the DataTemplate-ContentControl information and just do it .DataContext = new SomeViewModel (); in code.

The cleanest way I can connect a VM to Views is to use the ViewModelLocator template. Google ViewModelLocator.

+2
source

There are several easy ways to simply bind a ViewModel to a view. As Elad said, you can add it to the code:

 _vm = new MarketIndexVM(); this.DataContext = _vm; 

or you can specify the ViewModel as a resource in your XAML of your view:

 <UserControl.Resources> <local:CashFlowViewModel x:Key="ViewModel"/> <Converters:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/> </UserControl.Resources> 

and bind the DataContext of your LayoutRoot to this resource:

 <Grid x:Name="LayoutRoot" DataContext="{StaticResource ViewModel}"> 
+1
source

This may not directly answer your question, but have you looked at using the MVVM structure? For example, in Caliburn.Micro you would do (a very simple example):

 public class ShellViewModel : Conductor<IScreen> { public ShellViewModel() { var myViewModel = new MyViewModel(); this.ActivateItem(myViewModel); } } 

ShellView.xaml

 <Grid> <ContentControl x:Name="ActiveItem" /> </Grid> 

Myview.xaml

 <Grid> <TextBlock>Hello world</TextBlock> </Grid> 

This is the first viewmodel approach.

0
source

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


All Articles