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

Uno Platform 5中如何从页面获取MainModel实例

问题:Uno Platform中无法正确访问MainModel以实现屏幕日志功能

我正在使用Uno Platform模板,尝试添加屏幕日志以便在测试时查看Android设备上的错误。现有页面及代码可正常运行,但从依赖注入的Observable中读取日志消息时,无法正确访问MainModel:

  • 页面构造函数中DataContext为null
  • OnNavigatedTo方法初始获取到的是ShellModel,仅在跳转至其他页面返回后才会得到正确的MainModel

已知MainModel已成功创建({Binding Title}可正常工作),若直接在页面中实例化MainModel会触发依赖注入相关报错。

页面XAML代码

<Page x:Class="Phirenze.Phinance.Uno.Presentation.MainPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:utu="using:Uno.Toolkit.UI"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:not_maui="http://notmaui"
      mc:Ignorable="d not_maui"
      NavigationCacheMode="Required"
      Background="{ThemeResource BackgroundBrush}">
    <Grid utu:SafeArea.Insets="VisibleBounds">
      <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="200px" />
      </Grid.RowDefinitions>
      <utu:NavigationBar Content="{Binding Title}" />

      <ScrollViewer x:Name="ScrollViewer">
        <StackPanel x:Name="LogStackPanel"/>
      </ScrollViewer>
    </Grid>
</Page>

后台C#代码

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        InitializeComponent();
        LogMessage("Message log");
    }

    private void LogMessage(string message)
    {
        LogStackPanel.Children.Add(new TextBlock { Text = message });
        LogStackPanel.UpdateLayout();
        ScrollViewer.ChangeView(null, ScrollViewer.ScrollableHeight, null);
    }
}

MainModel代码

public partial record MainModel(IObservable<LogEvent> observable)
{
    public IObservable<LogEvent> Observable { get; } = observable;
    public string Title { get; } = "Main";
}

版本信息

  • .NET: 9.0.200
  • Uno.Platform: 5.6.45
  • Uno.Extensions.Hosting: 5.2.7
  • Uno.Wasm.Bootstrap: 9.0.11

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 21:33:18