c# - 无法在 WPF MVVM 中将 View 绑定(bind)到 ViewModel

标签 c# wpf mvvm binding

我正在 WPF 中开发桌面应用程序,我想遵循 MVVM 模式。我已经准备好 View ,是时候做一个 View 模型了。但由于某种原因,我无法将 View 模型绑定(bind)到 View 。
我已经在 View 的 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();
}

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

View 模型:
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";
          }
    }

以及我如何绑定(bind)属性:
<TextBlock Text="{Binding Path= BindingTest}" Padding="10"/>

这是我的文件的外观:

This is how my files look

最佳答案

如果你想在 XAML 中设置 DataContext,你应该这样做:

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

更改组件名称 到您的项目名称。

关于c# - 无法在 WPF MVVM 中将 View 绑定(bind)到 ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58833378/

相关文章:

wpf - 如果内容适合,则禁用 ScrollViewer VerticalScrollBarVisible

c# - 如何将参数发送到 ICommand 的 Execute 方法

C#http Post在webresponse中没有得到任何东西

c# - Mono 仅在某些计算机上获得 "System.ExecutionEngineException: SIGILL "

c# - Azure Blob TIFF 到 PNG 转换,无需下载

c# - 从数据行 View WPF 中获取数据网格行

c# - 快速 WPF 粒子背景

c# - 探索为每个使用它的 ViewModel/Class 设置 DbContext 的陷阱(如果有的话)

wpf - WPF MVVM-在TreeViewItem中触发事件的最正确方法是什么

c# - 使用 log4net 登录到 Oracle 数据库不会立即更新数据库