如何使用SelectorBar、Frame和依赖注入

问题描述 投票:0回答:1

我使用 WinUi 3、社区工具包 mvvm 和 Net 8.0,使用 c# 作为语言。 我有一个概述页面,它应该以两种可能的方式显示项目集合。 在 App.xaml.cs 中,我添加了以下页面以供 DI 加载。

  services.AddTransient<OverviewPage>();
  // Subpages of OverviewPage
  services.AddTransient<Page1>();
  services.AddTransient<Page2>();

您应该能够在列表视图或数据网格中查看项目。为此,我添加了带有 SelectionChanged-Event 和 Frame 的 SelectorBar 控件。

概览页面.xaml

 <Grid x:Name="ContentArea">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="9*" />
    </Grid.RowDefinitions>        
    <SelectorBar Grid.Row="0" SelectionChanged="SelectorBar_OnSelectionChanged">
        <SelectorBarItem Text="All" IsSelected="True"/>
        <SelectorBarItem Text="Page1" />
        <SelectorBarItem Text="Page2" />
    </SelectorBar>
    <Frame Grid.Row="1" IsNavigationStackEnabled="False" x:Name="ContentFrame"/>
</Grid>

概览页面.xaml.cs

    private void SelectorBar_OnSelectionChanged(...) {
        var currentSelectedItem = sender.SelectedItem;
        var currentSelectedIndex = sender.Items.IndexOf(currentSelectedItem);
        var pageType = currentSelectedIndex switch {
            0 => typeof(Page1),
            1 => typeof(Page2),
            _ => throw new("invalid page index")
        };

        var slideNavigationTransitionEffect = currentSelectedIndex - _previousHistorySelectorBarIndex > 0 ? SlideNavigationTransitionEffect.FromRight : SlideNavigationTransitionEffect.FromLeft;

        HistoryContentFrame.Navigate(pageType, null, new SlideNavigationTransitionInfo() { Effect = slideNavigationTransitionEffect });

        _previousHistorySelectorBarIndex = currentSelectedIndex;
    }

这两个页面旨在在加载并运行时通过 Messenger 请求项目。

我的问题是,每次更改选择时,Page1 和 Page2 都会一次又一次创建。但我不希望这样,我希望 Page1 和 Page2 创建一次,并在 OverviewPage 被处置时被处置。 首先我想我可以使用 AddScoped 添加子页面,但我不知道该怎么做。有人知道如何实现这一目标吗?这可能吗?

致以诚挚的问候

c# .net dependency-injection winui-3 community-toolkit-mvvm
1个回答
0
投票

您每次都在创建一个新的页面实例。所以你需要存储页面实例并重用它。

Type page1;
Type page2;

Type pageType;
switch (currentSelectedIndex)
{
  Case 0:
  if (page1 == null)
      page1 = typeof(Page1);
  pageType = page1;
  break;
  Case 1:
  if (page2 == null)
      page2 = typeof(Page2);
  pageType = page2;
  break;
}
© www.soinside.com 2019 - 2024. All rights reserved.