You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用MVVM Community Toolkit在Avalonia中实现导航遇视图找不到问题

Avalonia + MVVM Community Toolkit 导航异常:ContentPresenter无法加载HomeView

问题描述

我在Avalonia项目中基于MVVM Community Toolkit实现基础导航:

  • 主窗口添加ContentPresenter,将其Content绑定到CurrentPage属性
  • 创建了HomeView及对应的HomeViewModel
  • 仅新增了ContentPresenter和首页相关的视图、视图模型,其余代码为项目自动生成

预期ContentPresenter能显示HomeView.axaml的内容,但运行时无法定位到该视图。项目自带自动生成的ViewLocator,用于根据ViewModel匹配对应视图,逻辑看似正常,但就是找不到HomeView。我尝试在HomeView构造函数中手动设置DataContext,问题仍未解决。

相关代码

MainWindow.axaml(仅ContentPresenter为新增)

<Window xmlns="https://github.com/avaloniaui"
        ...>

    <Design.DataContext>
        <!-- This only sets the DataContext for the previewer in an IDE,
             to set the actual DataContext for runtime, set the DataContext property in code (look at App.axaml.cs) -->
        <vm:MainWindowViewModel />
    </Design.DataContext>

        <ContentPresenter Content="{Binding CurrentPage}" />
</Window>

MainWindowViewModel.cs

using CommunityToolkit.Mvvm.ComponentModel;

namespace AvaloniaApplication5.ViewModels
{
    public partial class MainWindowViewModel : ViewModelBase
    {
        [ObservableProperty]
        private ViewModelBase _currentPage = new HomeViewModel();
    }
}

HomeView.axaml

<UserControl xmlns="https://github.com/avaloniaui"
             ...>
    Welcome to Avalonia!
</UserControl>

HomeViewModel.cs

namespace AvaloniaApplication5.ViewModels
{
    public class HomeViewModel : ViewModelBase
    {
    }
}

ViewLocator.cs(自动生成)

using Avalonia.Controls;
using Avalonia.Controls.Templates;
using AvaloniaApplication5.ViewModels;
using System;

namespace AvaloniaApplication5
{
    public class ViewLocator : IDataTemplate
    {

        public Control? Build(object? data)
        {
            if (data is null)
                return null;

            var name = data.GetType().FullName!.Replace("ViewModel", "View", StringComparison.Ordinal);
            var type = Type.GetType(name);

            if (type != null)
            {
                var control = (Control)Activator.CreateInstance(type)!;
                control.DataContext = data;
                return control;
            }

            return new TextBlock { Text = "Not Found: " + name };
        }

        public bool Match(object? data)
        {
            return data is ViewModelBase;
        }
    }
}

HomeView.axaml.cs(尝试添加的代码)

public HomeView()
{
    InitializeComponent();
    DataContext = new HomeViewModel();
}

内容的提问来源于stack exchange,提问作者Cenax

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 20:57:34