It'sNotALie.
It'sNotALie.

Reputation: 22794

WPF Resources not loading?

Alright, so I've got a bit of XAML that doesn't seem to want to work. It's meant show the value of "MainWindowViewModel.Property" but it doesn't do that.

First, the code:

MainWindow.xaml:

<Window x:Class="MyNamespace.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MyNamespace"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <local:MainWindowViewModel x:Key="ViewModel"/>
    </Window.Resources>
    <Grid>
        <Label Content="{Binding Property, Source={StaticResource ViewModel}}"/>
    </Grid>
</Window>

MainWindow.xaml.cs:

namespace MyNamespace
{
    public partial class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}

MainWindowViewModel.cs

namespace MyNamespace
{
    public class MainWindowViewModel
    {
        public string Property = "test";
    }
}

This seems pretty correct to me but it doesn't work in runtime and the designer gives me a cryptic error:

PropertyPath
 Property expected

Around the "Property" in the Binding. Any ideas why this could be?

Thanks!

Upvotes: 1

Views: 636

Answers (3)

Grx70
Grx70

Reputation: 10349

The problem here is that the Property member of your MainWindowViewModel is a field and not a property, and WPF only supports binding to properties. So your view model should look at least something like this:

namespace MyNamespace
{
    public class MainWindowViewModel
    {
        public MainWindowViewModel()
        {
            Property = "test";
        }

        public string Property { get; set; }
    }
}

If you're planning on changing the value through the course of the life of your view model you might also consider implementing INotifyPropertyChanged.

Upvotes: 5

rohHit naik
rohHit naik

Reputation: 11

Try this :

In your ViewModel make a Property by name Property like:

private string _property;
public string Property
{
    get{ return _property;}
    set{ _property = value;}
}


public MainWindowViewModel()
{
    Property = "test";
}

Upvotes: -1

Tyress
Tyress

Reputation: 3653

Instead of

<Window.Resources>
    <local:MainWindowViewModel x:Key="ViewModel"/>
</Window.Resources>

I believe you should do:

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

and bind as:

    <Label Content="{Binding Property}"/>

Also take note of your namespaces:

xmlns:local="clr-namespace:MyNamespace" 

but your viewmodel seems to be somewhere else

Upvotes: 2

Related Questions