我正在 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"/>
这是我的文件的外观:
最佳答案
如果你想在 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/