繁体   English   中英

XAML 框架从未为表单行为调用 OnDetachingForm

[英]OnDetachingForm never called by XAML framework for Form Behaviors

我试图找到一种使用表单行为的好方法来确保用户只能将所需的输入输入到条目控件中。 我的问题是 xaml 框架永远不会调用 OnDetachingFrom 方法。 这会导致内存丢失,因为我订阅了 Entry 控件的 TextChanged 事件以修改其行为,并且无法取消订阅。

我试图找到一种“干净”的方式来跟踪当页面弹出堆栈时需要清除哪些控件的行为(我必须使用主导航页面跟踪自己)但我能想到的正在命名每个控件,在后面的代码中将控件添加到页面上的集合,使用“清除”方法在页面上实现一个接口,该方法在调用 OnDetachingForm 的集合中的每个控件上执行 xxx.Behaviors.Clear()每个控件的方法。

这似乎有点可怕,与“干净”相反。 我希望有人知道更好的方法。 由于像这样的设计疏忽,我从来没有真正喜欢 XAML 和 MVVM。 希望我所有的谷歌搜索都错过了一些东西。

对于我的行为,我几乎是从 Microsoft 教程页面复制的。
https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/behaviors/creating

namespace StoreTrak.Behaviors
{
    public class IntegerValidationBehavior : Behavior<Entry>
    {
        protected override void OnAttachedTo(Entry bindable)
        {
            if (bindable != null)
                bindable.TextChanged += OnEntryTextChanged;
            base.OnAttachedTo(bindable);
        }

        /// <summary>
        /// This NEVER gets called by the XAML framework.
        /// </summary>
        /// <param name="bindable"></param>
        protected override void OnDetachingFrom(Entry bindable)
        {
            if (bindable != null)
                bindable.TextChanged -= OnEntryTextChanged;
            base.OnDetachingFrom(bindable);
        }

        private static void OnEntryTextChanged(object sender, TextChangedEventArgs args)
        {
            if (string.IsNullOrEmpty(args.NewTextValue))
            {
                ((Entry)sender).Text = "0";
                return;
            }

            if (!int.TryParse(args.NewTextValue, out int x))
                ((Entry)sender).Text = args.OldTextValue;
        }
    }
}

然后我只是做了一个基本的实现。

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
             xmlns:vm="clr-namespace:StoreTrak.ViewModels"
             xmlns:behaviors="clr-namespace:StoreTrak.Behaviors"
             x:Class="StoreTrak.Pages.TestPage">
    <ContentPage.BindingContext>
        <vm:TestViewModel />
    </ContentPage.BindingContext>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>

        <Label Text="Field 1" Grid.Row="0" Grid.Column="0" />
        <Entry Text="{Binding Field1}" Grid.Row="0" Grid.Column="1" />

        <Label Text="Field 2" Grid.Row="2" Grid.Column="0" />
        <StackLayout Grid.Row="2" Grid.Column="1" Margin="0" Padding="0">
            <Entry x:Name="Field2" Text="{Binding Field2}">
                <Entry.Behaviors>
                    <behaviors:IntegerValidationBehavior />
                </Entry.Behaviors>
            </Entry>
            <Label Text="Error number 1" TextColor="Red" FontSize="Small" IsVisible="False" />
            <Label Text="Error number 2" TextColor="Red" FontSize="Small" IsVisible="True" />
            <Label Text="Error number 3" TextColor="Red" FontSize="Small" IsVisible="False" />
        </StackLayout>
        <Label Text="Field 3" Grid.Row="3" Grid.Column="0" />
        <Entry Text="{Binding Field3}" Grid.Row="3" Grid.Column="1" />
    </Grid>

那么我如何才能触发该事件呢? 我能找到的唯一方法是打电话

Field2.Behaviors.Clear();

但我在哪里称呼它? 我不能把它放在 OnApprearing 中,因为它可以在导航到新页面时被调用,然后当这个页面再次显示时,行为就消失了。

/// <summary>
/// can be called when a new page is added to the stack
/// </summary>
protected override void OnDisappearing()
{
    base.OnDisappearing();
}

所以当页面从堆栈中移除时我需要清除它。 我怎么知道什么时候发生? 我能找到的唯一方法是在 MainPage 中收听主导航页面上的事件。
我还创建了一个接口 IPageDispose 并在我的页面上实现它。

    public partial class App : Application
    {
        public App()
        {
            InitializeComponent();

            MainPage = new NavigationPage(new Pages.MainPage());
            if (MainPage is NavigationPage page)
            {
                page.Popped += Page_Popped;
                page.PoppedToRoot += Page_PoppedToRoot;
            }
        }

        /// <summary>
        /// https://www.johankarlsson.net/2017/08/popped-pages-in-xamarin-forms.html
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Page_PoppedToRoot(object sender, NavigationEventArgs e)
        {
            if (e is PoppedToRootEventArgs args)
            {
                foreach(Page page in args.PoppedPages)
                    Page_Popped(sender, new NavigationEventArgs(page));
            }
        }

        private void Page_Popped(object sender, NavigationEventArgs e)
        {
            if (e.Page is IPageDispose ipd)
            {
                ipd.Dispose();
            }
        }

        protected override void OnStart()
        {
        }

        protected override void OnSleep()
        {
        }

        protected override void OnResume()
        {
        }

        public async static void HandleError(Exception ex)
        {
            Logger.Entry(ex);
            await Application.Current.MainPage.Navigation.PushModalAsync(new Pages.LogPages.LogPage(ex));
        }
    }
}

namespace StoreTrak.Pages
{
    public interface IPageDispose
    {
        void Dispose();
    }
}

public partial class TestPage : ContentPage, IPageDispose
{
    public TestPage()
    {
        InitializeComponent();
    }

    public void Dispose()
    {
        // How do I know which control to clear?
        // give each one a name and hardcode the Clear method?
        throw new NotImplementedException();
    }

现在,我怎么知道要清除哪些控件? 我做了这个复杂的过程,仍然需要命名控件并在后面的代码中跟踪它们? 这比在后面的代码中使用事件侦听器更好吗?

    public class _BasePage : ContentPage
    {
        protected void IntegerValidation_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (string.IsNullOrEmpty(e.NewTextValue))
            {
                ((Entry)sender).Text = "0";
                return;
            }

            if (!int.TryParse(e.NewTextValue, out int x))
                ((Entry)sender).Text = e.OldTextValue;
        }

    }
}

感谢您更新问题。

关于OnDetachingFrom方法,我们可以看看这个官方文档。

OnDetachingFrom方法在从控件中删除行为时触发,用于执行任何所需的清理,例如取消订阅事件以防止内存泄漏。 但是,除非通过RemoveClear方法修改了控件的 Behaviors 集合,否则不会从控件中隐式删除行为。

我们将看到OnDetachingFrom通常不会被触发,除非调用RemoveClear方法。

但我在哪里称呼它? 我不能把它放在 OnApprearing 中,因为它可以在导航到新页面时被调用,然后当这个页面再次显示时,行为就消失了。

我们可以在页面的OnDisappearing方法上调用clear方法,但也需要在进入页面时添加行为。

例如:

protected override void OnAppearing()
{
    base.OnAppearing();
    myentry.Behaviors.Add(new NumericValidationBehavior());
}


protected override void OnDisappearing()
{
    base.OnDisappearing();
    myentry.Behaviors.Clear();
}

================================更新================== ====================

您可以使用StyleTrigger for Entry ,然后不需要通过编码为每个Entry添加/检查行为。

创建一个NumericValidationBehavior类:

public class NumericValidationBehavior : Behavior<Entry>
{
    public static readonly BindableProperty AttachBehaviorProperty = 
        BindableProperty.CreateAttached ("AttachBehavior", typeof(bool), typeof(NumericValidationBehavior), false, propertyChanged: OnAttachBehaviorChanged);

    public static bool GetAttachBehavior (BindableObject view)
    {
        return (bool)view.GetValue (AttachBehaviorProperty);
    }

    public static void SetAttachBehavior (BindableObject view, bool value)
    {
        view.SetValue (AttachBehaviorProperty, value);
    }

    static void OnAttachBehaviorChanged (BindableObject view, object oldValue, object newValue)
    {
        var entry = view as Entry;
        if (entry == null) {
            return;
        }

        bool attachBehavior = (bool)newValue;
        if (attachBehavior) {
            entry.Behaviors.Add (new NumericValidationBehavior ());
        } else {
            var toRemove = entry.Behaviors.FirstOrDefault (b => b is NumericValidationBehavior);
            if (toRemove != null) {
                entry.Behaviors.Remove (toRemove);
            }
        }
    }

    protected override void OnAttachedTo (Entry entry)
    {
        entry.TextChanged += OnEntryTextChanged;
        base.OnAttachedTo (entry);
    }

    protected override void OnDetachingFrom (Entry entry)
    {
        entry.TextChanged -= OnEntryTextChanged;
        base.OnDetachingFrom (entry);
    }

    void OnEntryTextChanged (object sender, TextChangedEventArgs args)
    {
        double result;
        bool isValid = double.TryParse (args.NewTextValue, out result);
        ((Entry)sender).TextColor = isValid ? Color.Default : Color.Red;
    }
}

然后在ContentPage.Xaml 中

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:WorkingWithBehaviors;assembly=NumericValidationBehaviorStyle" x:Class="WorkingWithBehaviors.NumericValidationPage" Title="XAML" IconImageSource="xaml.png">
    <ContentPage.Resources>
        <ResourceDictionary>
            <Style TargetType="Entry">
                <Style.Triggers>
                    <Trigger TargetType="Entry"
                             Property="IsFocused"
                             Value="True">
                       
                        <Setter Property="local:NumericValidationBehavior.AttachBehavior"
                                Value="true" />
                        <!-- multiple Setters elements are allowed -->
                    </Trigger>
                    <Trigger TargetType="Entry"
                             Property="IsFocused"
                             Value="False">
                        
                        <Setter Property="local:NumericValidationBehavior.AttachBehavior"
                                Value="False" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </ResourceDictionary>
    </ContentPage.Resources>
    
    <StackLayout Padding="10,50,10,0">
        <Label Text="Red when the number isn't valid" FontSize="Small" />
        <Entry Placeholder="Enter a System.Double" />
    </StackLayout>
    
</ContentPage>

我把江小辈贴出来的答案标记为答案。 他的代码完全回答了我的问题。 然而,在我的项目中,我决定牺牲“代码背后没有代码”的理想,走一条更少部件和更少代码的路线。 我决定放弃 Behaviors,只为每种数据类型创建一个带有事件处理程序的基本 ContentPage 类。 然后我可以在每个条目中听他们。 虽然它不忠实于 XAML 的“无代码隐藏代码”,但对我来说更容易理解。 如果我对这种方法有任何问题,我很高兴有小江的替代方案。 谢谢!

using Xamarin.Forms;

namespace StoreTrak.Pages
{
    public class _BaseContentPage : ContentPage
    {
        #region Entry Event Validation

        protected void IntegerValidation_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (string.IsNullOrEmpty(e.NewTextValue))
            {
                ((Entry)sender).Text = "0";
                return;
            }

            if (!int.TryParse(e.NewTextValue, out int _))
                ((Entry)sender).Text = e.OldTextValue;
        }

        protected void NullIntegerValidation_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (string.IsNullOrEmpty(e.NewTextValue))
            {
                ((Entry)sender).Text = "";
                return;
            }

            if (!int.TryParse(e.NewTextValue, out int _))
                ((Entry)sender).Text = e.OldTextValue;
        }

        #endregion Entry Event Validation
    }
}

<?xml version="1.0" encoding="utf-8" ?>
<d:_BaseContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
             xmlns:d="clr-namespace:StoreTrak.Pages;assembly=StoreTrak"
             xmlns:vm="clr-namespace:StoreTrak.ViewModels"
             x:Class="StoreTrak.Pages.TestPage">
    <ContentPage.BindingContext>
        <vm:TestViewModel />
    </ContentPage.BindingContext> 
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>

        <!-- Field1 - string -->
        <Label Text="Field 1" Grid.Row="0" Grid.Column="0" />
        <StackLayout Grid.Row="0" Grid.Column="1" Margin="0" Padding="0">
            <Entry Text="{Binding Field1}" Grid.Row="0" Grid.Column="1" />
            <Label Text="Error number 1" TextColor="Red" FontSize="Small" IsVisible="False" />
        </StackLayout>

        <!-- Field2 -int -->
        <Label Text="Field 2" Grid.Row="2" Grid.Column="0" />
        <StackLayout Grid.Row="2" Grid.Column="1" Margin="0" Padding="0">
            <Entry Text="{Binding Field2}" TextChanged="IntegerValidation_TextChanged" />
            <Label Text="Error number 2" TextColor="Red" FontSize="Small" IsVisible="False" />
        </StackLayout>

        <!-- Field3 -int? -->
        <Label Text="Field 3" Grid.Row="3" Grid.Column="0" />
        <StackLayout Grid.Row="3" Grid.Column="1" Margin="0" Padding="0">
            <Entry Text="{Binding Field3}" TextChanged="NullIntegerValidation_TextChanged" />
            <Label Text="Error number 3" TextColor="Red" FontSize="Small" IsVisible="False" />
        </StackLayout>
    </Grid>
</d:_BaseContentPage>

using Xamarin.Forms.Xaml;

namespace StoreTrak.Pages
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class TestPage : _BaseContentPage
    {
        public TestPage()
        {
            InitializeComponent();
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM