C#/XAML MVVM:命名空间中的DataTemplate的 DataType不存在

后端开发 2026-07-10

我对WPF和 MVVM格式是新手,但我正在尝试把ListBox绑定到一个 ObservableCollection<Item>,其中 Item 是我在 ViewModel 命名空间中编写的自定义类型。

在我的视图xaml中,我能够将ListBox的 ItemSource 绑定到我的 Items 属性,使用如下:

ItemSource="{Binding Items}"

并且它能看到它。但是对于 DataTemplate 属性 DataType,我无法将它设置为 {x:Type viewmodel:Item},因为VS抛出错误

名称 "Item" 在命名空间 "clr-namespace:SBCM.MVVM.ViewModel" 中不存在

这是我的 PackManagerView.xaml

<UserControl x:Class="SBCM.MVVM.View.PackManagerView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:SBCM.MVVM.View" xmlns:core="clr-namespace:SBCM.Core" xmlns:viewmodel="clr-namespace:SBCM.MVVM.ViewModel"
             mc:Ignorable="d"
             d:DesignHeight="505" d:DesignWidth="700" Loaded="UserControl_Loaded"
             >
    <UserControl.DataContext>
        <viewmodel:PackManagerViewModel/>
    </UserControl.DataContext>
...
        <ListBox Background="#37306e"
                 Grid.Row="1"
                 Grid.ColumnSpan="2"
                 Grid.RowSpan="5"
                 Margin="10"
                 Name="packs_Listbox"
                 ItemsSource="{Binding Items}">

            <ListBox.ItemTemplate>
                <DataTemplate DataType="{x:Type viewmodel:Item}">

                </DataTemplate>
            </ListBox.ItemTemplate>

        </ListBox>
...
</UserControl>

这是我的 PackManagerViewModel 类:

namespace SBCM.MVVM.ViewModel;

class PackManagerViewModel
{
    public ObservableCollection<Item> Items { get; } = new();

    public PackManagerViewModel()
    {
    }

    // ...
}

public class Item
{
    public Item()
    {
    }

    public string IniLocation { get; set; }
    public string Title { get; set; }
    public string Id { get; set; }
    public Range IdRange { get; set; }
    public string ImageSrc { get; set; }
}

使用mvvm形式,所有视图都在 SBCM.MVVM.View 命名空间中,而我尝试运行的后端代码在 SBCM.MVVM.ViewModel 命名空间中。

我也尝试把所有后端代码放到 PackManagerView.xaml.cs 以实现绑定,但那样连 Items 都绑定不上。正如我前面所说,我对WPF和 MVVM形式还是新手,所以现在有些束手无策。

解决方案

我终于弄清楚了,命名空间是正确的,但必须先构建项目,XAML才能看到这些属性。我当时在跟一个教程,但它没提到这一点。构建完成后,我回到XAML视图,数据绑定就能正确地看到。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章