简体   繁体   中英

Can't bind View to ViewModel in WPF MVVM

I am working on desktop app in WPF and I want to follow the MVVM pattern. I have my view ready and it was time to do a viewmodel. But for some reason i can't bind viewmodel to the view. I have tried this in XAML of the view:

<Window x:Class="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:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
        mc:Ignorable="d"
        Title="" Height="626" Width="1200" Background="#FFDEDF1A"
        DataContext="ViewModels/MainViewModel">

Didn't work so i tried this in the class of View:

public MainWindow()
{
    this.DataContext = new MainViewModel(); 
    InitializeComponent();
}

But it doesn't work either... I tried to look it up on the internet but everyone is doing the same thing.

ViewModel:

class MainViewModel : INotifyPropertyChanged
    {
        public string BindingTest { get; set; }
        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

        public MainViewModel()
        {
            BindingTest = "test";
          }
    }

And how I binded the property:

<TextBlock Text="{Binding Path= BindingTest}" Padding="10"/>

This is how my files look:

这就是我的文件的样子

If you want to set the DataContext in XAML, you should do something like this:

<Window x:Class="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:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
        xmlns:viewModels="clr-namespace:AssemblyName.ViewModels"
        mc:Ignorable="d"
        Title="" Height="626" Width="1200" Background="#FFDEDF1A">
        <Window.DataContext>
             <viewModels:MainViewModel />
        </Window.DataContext>
        <!-- Your Code Here... -->
</Window>

Change the AssemblyName to your project name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM