[英]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.我正在 WPF 中开发桌面应用程序,我想遵循 MVVM 模式。 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:
我在视图的 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">
Didn't work so i tried this in the class of View:没用,所以我在查看的 class 中尝试了这个:
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:如果你想在 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>
Change the AssemblyName to your project name.将AssemblyName更改为您的项目名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.