在MVVM WPF应用程序中使用本地ViewModel

3
我在处理视图时遇到了访问ViewModel的问题。
我的项目名为BankManagerApplication。其中包含与新的WPF应用程序相关的各种文件。我创建了三个不同的文件夹:Model,ViewModel和View。
目前,在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-namespace:BankManagerApplication.ViewModel" 中不存在

我刚开始学习 WPF,这个错误让我在还没真正开始之前就很困扰。


1
你已经构建包含 ViewModel 的项目了吗? - Dutts
通常,ViewModel 会被分配给常规视图控件(如窗口、网格或其他控件)的数据源。在视图的 XAML 中“new-up”一个 ViewModel 是相当不寻常的。 - JDB
1
此外,您无法将该类添加到网格中。它不允许作为网格的子项。 - dowhilefor
1个回答

2

由于它不是UI元素,因此您无法将其添加到网格控件中。您的视图模型将成为视图的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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接