【问题标题】:Can't bind View to ViewModel in WPF MVVM无法在 WPF MVVM 中将 View 绑定到 ViewModel
【发布时间】:2019-11-13 08:54:18
【问题描述】:

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

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

视图模型:

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

这是我的文件的外观:

【问题讨论】:

  • 从 XAML 中删除 DataContext="ViewModels/MainViewModel"。这是毫无意义的,而且在语法上也是错误的。
  • InitializeComponent(); 必须是构造函数中的第一件事。
  • 尝试把 DataContext = new MainViewModel();在 InitializeComponent(); 之后
  • @BarryO'Kane 错了。顺序根本不重要。
  • 视图模型是什么样的?它有公共属性吗?你如何绑定到他们?如果没有这些细节,我们将无能为力。

标签: c# wpf mvvm binding


【解决方案1】:

如果你想在 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>

AssemblyName 更改为您的项目名称。

【讨论】:

  • 实际上这行得通。感谢您先生和@Clemens。
猜你喜欢
  • 1970-01-01
  • 2012-03-18
  • 1970-01-01
  • 2011-11-07
  • 2013-08-29
  • 1970-01-01
  • 1970-01-01
  • 2011-02-08
  • 1970-01-01
相关资源
最近更新 更多