Home > OS >  What am I doing wrong connect viewmodel to view?
What am I doing wrong connect viewmodel to view?

Time:01-02

Can someone tell me what am I doing wrong? I have already tried everything, the pirmers that I downloaded from the Internet work, I made a minimal example, but it does not work.

I can't connect mine ViewModel in View

<Grid>
    <Grid.Resources>
        <DataTemplate DataType="{x:Type local:TestViewModel}">
            <Label Content="{Binding Wtf}"/>
        </DataTemplate>
    </Grid.Resources>
</Grid>
public class TestViewModel 
{
    public string Wtf => "wtf???";

    public TestViewModel() {}
}

I'm trying to connect the view model like this, so that I can use dependency injection later. But my Binding "wtf" does not display

CodePudding user response:

The two standard ways of assigning the ViewModel to the View are

1] In the Xaml - this only works if your ViewModel has a paramaterless constructor.

<Window ... >    
    <Window.DataContext>
        <local:MainViewModel />
   </Window.DataContext>

  ...

</Window>

2] In the code behind constructor of the View - you can use an IoC container for injected services to the ViewModel.

public MainView()
{
    DataContext = new MainViewModel();
    InitializeComponent();
}

or

public MainView()
{
    DataContext = IoCContainer.GetInstance<MainViewModel>();
    InitializeComponent();
}

For more details, including a more advanced way to assign the ViewModel that will provide data at design time, check out my blog post.

CodePudding user response:

The code provided is not showing the whole thing. There are 2 missing parts :

  1. In the code behind instantiate the "TestViewModel" and put it in the DataContext.
  2. Introduce a "ContentControl" that its DataContext was created as mentioned above.

The DataTemplate is just a declaration and not making the presentation. The technique you are attempting to use is somehow advanced. It tells WPF that when a given class is encountered by a ContentControl , the Data Template is being used.

    <Grid>
            <Grid.Resources>
                <DataTemplate DataType="{x:Type local:TestViewModel}">
                    <Label Content="{Binding Wtf}"/>
                </DataTemplate>
                
            </Grid.Resources>
            <ContentControl Content="{Binding }"/>
        </Grid>
    public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
                DataContext = new TestViewModel();
            }
        }
  • Related