在处理视图时,我无法访问ViewModel。
我有一个名为 BankManagerApplication 的项目。在其中,我有与新的WPF应用程序相关的各种文件。我创建了三个单独的文件夹模型, ViewModel 和查看。
目前Model文件夹中有一个UserModel类,其中包含以下字段;
namespace BankManagerApplication.Model
{
public class UserModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public double AccountBallance { get; set; }
}
}
View文件夹中的空白视图,里面只有一个网格;
<Window x:Class="BankManagerApplication.View.MainWindowView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindowView" Height="300" Width="300">
<Grid>
</Grid>
</Window>
以及ViewModel文件夹中的空白ViewModel;
namespace BankManagerApplication.ViewModel
{
public class MainWindowViewModel
{
}
}
当我尝试像我这样在我的XAML中引用ViewModel时;
<Window x:Class="BankManagerApplication.View.MainWindowView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindowView" Height="300" Width="300"
xmlns:viewmodel="clr-namespace:BankManagerApplication.ViewModel">
<Grid>
<viewmodel:MainWindowViewModel></viewmodel:MainWindowViewModel>
</Grid>
</Window>
我收到错误
命名空间中不存在名称'MainWindowViewModel “CLR-名称空间:BankManagerApplication.ViewModel'
我刚刚开始学习WPF,这个错误在我真正开始之前就把我抛弃了
答案 0 :(得分:1)
您无法将其添加到网格控件,因为它不是UIElement。您的viewmodel将是您视图的DataContext:
<Window x:Class="BankManagerApplication.View.MainWindowView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindowView" Height="300" Width="300"
xmlns:viewmodel="clr-namespace:BankManagerApplication.ViewModel">
<Window.DataContext>
<viewmodel:MainWindowViewModel></viewmodel:MainWindowViewModel>
</Window.DataContext>
<Grid>
</Grid>