【问题标题】:Xamarin Forms: Is there a ViewDisappeared event for ViewElement?Xamarin Forms:ViewElement 是否有 ViewDisappeared 事件?
【发布时间】:2021-09-27 03:30:57
【问题描述】:

我一直在尝试处理 ViewElement/View,当 Page 在 Xamarin Forms 中显示它不再位于 NavigationStack 之上时。

似乎有一个来自 Xamarin 社区工具包的名为 LifecycleEffect 的新效果可以做到这一点,但是当新页面放在 NavigationStack 顶部时,Unloaded 事件不会触发(因此视图元素不会被删除,也不会触发事件)。

有没有人知道我可以在View 上绑定的事件让我确定它没有显示,但仍在NavigationStack 某处?

我真的希望 View 自己做这件事,而不是使用 Page

提前致谢:)

【问题讨论】:

  • 可能会覆盖不再显示的页面的OnDisappearing
  • 我不想使用Page 为我执行此操作,我希望View 自己知道这一点,而无需页面的帮助。

标签: xamarin xamarin.forms xamarin-community-toolkit


【解决方案1】:

AFAIK 没有平台这样做,因为它有点贵(对于几乎不需要的东西):每次隐藏或显示页面时,都必须在屏幕上的每个可视元素上执行一个方法。

唯一的解决方案(我知道)是让这个视图向它所在的页面添加一个“事件处理程序”,然后让页面的 OnDisappearing 调用该事件处理程序。定义一个公开“AddActionOnDisappearing”方法的接口。在可能具有此视图的页面上实现该接口。

第一版:手工编码的解决方案:

public interface IActionOnDisappearing
{
    void AddActionOnDisappearing(Action action)
    {
    }
}

public partial class MyPage : IActionOnDisappearing
{
    ...
    public void AddActionOnDisappearing(Action action)
    {
        ... remember the action somewhere ...
    }
    protected override void OnDisappearing()
    {
        ... call that action or event handler ...
        ...
    }
}

public partial class MySpecialView
{
    // constructor
    void MySpecialView(IActionOnDisappearing owningPage)
    {
        ...
        TellMeThePage(owningPage);
    }

    public void TellMeThePage(IActionOnDisappearing owningPage)
    {
        owningPage.AddActionOnDisappearing( () =>
           ... whatever you need to do ...
           );
    }

}

请注意,视图构造函数需要一个参数。 另一种方法是让 XAML 在页面上构建视图,给该视图一个 x:Name 属性,然后在页面的构造函数中,在 InitializeComponent 之后,将两者连接起来:

public partial class MyPage : IActionOnDisappearing
{
    // constructor
    void MyPage()
    {
        InitializeComponent();
        this.NameOfMySpecialView.TellMeThePage(this);
        ...
    }
}


public partial class MySpecialView
{
    // constructor
    void MySpecialView()
    {
        ...
    }

    public void TellMeThePage(IActionOnDisappearing owningPage)
    ...
}

我省略了 MyPage 需要的事件处理程序的详细信息。谷歌以获取有关该主题的信息。


第二版

上述解决方案要求页面知道它有这样的视图。并为该视图命名。并在构造函数中添加一行代码。

为了更容易编码,请在某处定义:

public static void TellMySpecialDescendents(Page owner)
{
    ... search all children and their children
    ... any that are of type `MySpecialView`, call
        ((MySpecialView)child).TellMeThePage(owner);
}

定义class BasePage,实现IActionOnDisappearing。任何可能有这种视图的类都继承自 BasePage。

并从此类页面的构造函数中调用TellMySpecialDescendents。当然是在InitializeComponent 之后。

如果您有多个这样的视图类型需要了解其所有者,请定义一个接口:

public interface IViewOnDisappearing
{
    void TellMeThePage(IActionOnDisappearing owningPage);
}

public partial class MySpecialView : IViewOnDisappearing
...

并将MySpecialView 使用替换为IViewOnDisappearing

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-02
    • 2017-07-28
    相关资源
    最近更新 更多