在WPF MVVM中无法将View绑定到ViewModel

我正在WPF中处理桌面应用程序,我想遵循MVVM模式。我已经准备好视图,是时候进行视图模型了。但是由于某种原因,我无法将viewmodel绑定到视图。 我已经在视图的XAML中尝试过此操作:

<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">

没有用,所以我在View类中尝试了此操作

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

但是它也不起作用...我试图在互联网上查找它,但是每个人都在做同样的事情。

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";
          }
    }

以及我如何绑定属性:

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

这是我的文件的外观:

在WPF MVVM中无法将View绑定到ViewModel

gansinimabi 回答:在WPF MVVM中无法将View绑定到ViewModel

如果要在XAML中设置DataContext,则应执行以下操作:

D:\Boot_Order>powershell.exe -ExecutionPolicy Bypass -File D:\Boot_Order\\test.ps1
Not ok

D:\Boot_Order>ECHO
123

D:\Boot_Order>Exit /b 123

AssemblyName 更改为您的项目名称。

本文链接:https://www.f2er.com/3111644.html

大家都在问