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

Avalonia C#:如何将UserControl作为SplitView内容显示?

Avalonia ViewLocator无法找到HomePageView的问题分析与解决

问题背景

使用VS2022 Avalonia MVVM模板开发应用,布局中SplitView的Content区域通过TransitioningContentControl绑定CurrentPage(初始为HomePageViewModel实例),但运行及设计器中均提示“Not Found: NewApp.Views.HomePageView”,文件实际存在且命名看似正确。

核心原因

  1. 命名空间不匹配:默认ViewLocator遵循约定:ViewModel所在命名空间为xxx.ViewModels,对应View需在xxx.Views命名空间下。当前HomePageView的命名空间是NewApp,而非NewApp.Views,不符合ViewLocator的查找逻辑。
  2. 访问修饰符限制:HomePageViewModel和HomePageView默认是internal访问级别,ViewLocator通过反射查找对应View时无法访问internal类型。
  3. XAML语法错误:MainWindow.axaml中的SplitView标签缺少闭合的>,可能导致布局解析异常。

解决步骤

  1. 调整View的命名空间
    • 将HomePageView移动到项目的Views文件夹中,或手动修改XAML和代码隐藏类的命名空间为NewApp.Views。
  2. 修改访问修饰符为public
    • 确保HomePageView和HomePageViewModel的类修饰符为public,让ViewLocator可以正确识别并反射实例化。
  3. 修复XAML语法错误
    • 补全SplitView标签的闭合符号,保证布局解析正常。

修正后的代码示例

1. HomePageView.axaml(修正命名空间)

<UserControl xmlns="https://github.com/avaloniaui"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
         x:Class="NewApp.Views.HomePageView"
         xmlns:vm="using:NewApp.ViewModels">
  Welcome to Avalonia!
</UserControl>

2. HomePageView.axaml.cs(改为public)

namespace NewApp.Views;

public partial class HomePageView : UserControl
{
    public HomePageView()
    {
        InitializeComponent();
    }
}

3. HomePageViewModel.cs(改为public)

namespace NewApp.ViewModels
{
    public class HomePageViewModel : ViewModelBase
    {

    }
}

4. MainWindow.axaml(修复SplitView标签)

<StackPanel>
  <SplitView IsPaneOpen="{Binding IsPagePaneOpen}"
             OpenPaneLength="150"
             CompactPaneLength="50"
             DisplayMode="CompactInline">
    <SplitView.Pane>
      <StackPanel>
        <ListBox>
          <ListBoxItem>A</ListBoxItem>
          <ListBoxItem>B</ListBoxItem>
        </ListBox>
        <Button Command="{Binding TriggerPagePaneCommand}">
          -
        </Button>
      </StackPanel>
    </SplitView.Pane>
    <SplitView.Content>
      <Border>
        <TransitioningContentControl Content="{Binding CurrentPage}"/>
      </Border>
    </SplitView.Content>
  </SplitView>
</StackPanel>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 03:08:12