我第一次在 VS2022 中使用 Avalonia,该应用程序包含一个由 SplitView 控件组成的基本布局,窗格中的 ListBox 充当侧边栏,当选择项目时,相关的 UserControl 应出现在SplitView 的内容侧。
我认为下面的代码应该可以在设计器中工作,而且当我运行应用程序时,我看到的不是 UserControl,而是“Not Found: NewApp.Views.HomePageView”。这很奇怪,因为它的位置和命名正确,该应用程序也是从 MVVM 模板创建的,并且包含 ViewLocator 文件。
任何人都可以帮我理解我错在哪里吗?
MainWindow.axaml 看起来像这样;
<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>
MainWindowViewModel 看起来像;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Drawing.Printing;
namespace NewApp.ViewModels
{
public partial class MainWindowViewModel : ViewModelBase
{
[ObservableProperty]
private bool _isPagePaneOpen = false;
[ObservableProperty]
private ViewModelBase _currentPage = new HomePageViewModel();
[RelayCommand]
private void TriggerPagePane()
{
IsPagePaneOpen = !IsPagePaneOpen;
}
}
}
UserControl View (HomePageView.axaml) 代码仅包含所有新文件中的基本文本,而 ViewModel (HomePageViewModel.cs) 为空,如下所示;
namespace NewApp.ViewModels
{
internal class HomePageViewModel : ViewModelBase
{
}
为了完整起见,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.HomePageView"
xmlns:vm="using:NewApp.ViewModels">
Welcome to Avalonia!
</UserControl>
ViewModel 不是视图。 ContentPresenter(例如 TransitioningContentControl)会很乐意尝试呈现任何对象,但呈现 ViewModel 不太可能是您的预期目标。
您需要的是一个视图,例如使用 ViewModel 作为 DataContext 的用户控件(尽管它可以是很多东西),然后使用 ContentPresenter 来呈现它。