In C #, how can I set a DataContext in a ViewModel?

I am trying to wrap my head around MVVM. I understand a lot, but it's hard for me to understand one aspect: Configuring a DataContext .

I want to show a view with a specific object. The user cannot decide what is visible, so I need to create a view in the code. Then I want to set the DataContext of the view to an object (for binding). I try not to put the code in the view for this, but View.LayoutRoot.DataContext is not public.

What am I missing?

trying to avoid this:

public class View
{
    public View(object dataContext)
    {
        InitializeComponent();
        LayoutRoot.DataContext = dataContext;  
    }
}

with something like this:

public class ViewModel
{
    ...

    public UIElement GetView()
    {
        UIElement *element = new View();
        element.LayoutRoot.DataContext = element;
        return element;
    }
}
+3
source share
2 answers

, ViewModel, .

, ViewModel .

MVVM ViewModel. WPF DataTemplates XAML.

+7

XAML Window ( , MVVM), LayoutRoot (Grid ) . , , .

, , Cameron - View, ModelView DataContext. - (DataTemplate, , , ), .

0

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


All Articles