David
David

Reputation: 263

Setting Window.Datacontext

I am trying to use my viewmodel as my window's datacontext but am getting the error:

ViewModel is not supported in a Windows Presentation Foundation (WPF) project.

Clearly, I am not understanding something about the syntax and databinding my window to my view model, but I am not sure what it is that I don't know.

Any advice on what I should be reading?

<Window x:Class="SunnyBeam.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="SunnyBeam" Height="488.358" Width="1014.552">
    <Window.DataContext>
        <ViewModel/>
    </Window.DataContext>
    <Grid>

    </Grid>
</Window>

Upvotes: 2

Views: 1646

Answers (3)

Skint007
Skint007

Reputation: 355

I thought I would throw in my experience with this error.

I had my datacontext setup same as below, and kept getting an error that ViewModel didn't exist, which I know it did. I refused to set it in code behind, simply rebuilding my project actually fixed this error.

<Window.DataContext>
    <ViewModel/>
</Window.DataContext>

Upvotes: 0

D J
D J

Reputation: 7028

define class like

 public class ViewModel
 {
    public string Name { get; set; }
    public ViewModel()
    {

    }
 }

Use it in xaml like

<Window x:Class="WpfApplication2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:ui="clr-namespace:WpfApplication2"
    Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
    <ui:ViewModel/>
</Window.DataContext>
<Grid>

</Grid>

It should work.

Upvotes: 1

Encarmine
Encarmine

Reputation: 453

Usually I set DataContext through codebehind like that:

public partial class Flor1 : Window
{
    public Flor1()
    {
        var dc = new MyViewModel();
        dc.LoadData();
        DataContext = dc;
        InitializeComponent();
    }
}

In place of MyViewModel may be anything you want to bind to.

Upvotes: 1

Related Questions