[英]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
方法在從控件中刪除行為時觸發,用於執行任何所需的清理,例如取消訂閱事件以防止內存泄漏。 但是,除非通過Remove
或Clear
方法修改了控件的 Behaviors 集合,否則不會從控件中隱式刪除行為。
我們將看到OnDetachingFrom
通常不會被觸發,除非調用Remove
和Clear
方法。
但我在哪里稱呼它? 我不能把它放在 OnApprearing 中,因為它可以在導航到新頁面時被調用,然后當這個頁面再次顯示時,行為就消失了。
我們可以在頁面的OnDisappearing
方法上調用clear
方法,但也需要在進入頁面時添加行為。
例如:
protected override void OnAppearing()
{
base.OnAppearing();
myentry.Behaviors.Add(new NumericValidationBehavior());
}
protected override void OnDisappearing()
{
base.OnDisappearing();
myentry.Behaviors.Clear();
}
================================更新================== ====================
您可以使用Style和Trigger 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.