gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:35:03 25 4
gpt4 key购买 nike

我在使用我的 View 时无法访问我的 ViewModel。

我有一个名为 BankManagerApplication 的项目。其中包含与新 WPF 应用程序关联的各种文件。我创建了三个单独的文件夹 ModelViewModelView

目前在 Model 文件夹中有一个 UserModel 类,具有以下字段;

namespace BankManagerApplication.Model
{
public class UserModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public double AccountBallance { get; set; }
}
}

View 文件夹中的一个空白 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>

我得到了错误

The name 'MainWindowViewModel does not exist in the namespace "clr-namespace:BankManagerApplication.ViewModel'

我才刚刚开始学习 WPF,在我真正开始学习之前这个错误让我失望

最佳答案

您不能将它添加到 Grid 控件,因为它不是 UIElement。您的 View 模型将是您 View 的 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>

关于c# - 在 MVVM WPF 应用程序中使用本地 ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18985702/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com