[英]Can't bind View to ViewModel in WPF MVVM
我正在 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">
沒用,所以我在查看的 class 中嘗試了這個:
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,你應該這樣做:
<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更改為您的項目名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.