简体   繁体   English

在哪里取消订阅 Xamarin.Forms 条目中的事件?

[英]Where to unsubscribe events in a Xamarin.Forms Entry?

I have a custom entry inheriting from Xamarin.Forms Entry to add a CompletedCommand Property.我有一个自定义条目继承自 Xamarin.Forms 条目以添加 CompletedCommand 属性。 For that, I subscribe to the Completed Event of the Xamarin.Forms Entry in the constructor and invoke the bindable Property Command.为此,我在构造函数中订阅了 Xamarin.Forms 条目的 Completed Event 并调用可绑定的属性命令。

My Question is, is it necessary to unsubscribe?我的问题是,有必要退订吗? If so, where is a good place to do that?如果是这样,哪里是这样做的好地方?

public class Entry : Xamarin.Forms.Entry
{
    public static readonly BindableProperty CompletedCommandProperty = BindableProperty.Create(
                                                     propertyName: nameof(CompletedCommand),
                                                     returnType: typeof(ICommand),
                                                     declaringType: typeof(Entry),
                                                     defaultValue: null,
                                                     defaultBindingMode: BindingMode.TwoWay);

    /// <summary>
    /// The Command to execute when this entry is completed (Enter pressed).
    /// </summary>
    public ICommand CompletedCommand
    {
        get => (ICommand)GetValue(CompletedCommandProperty);
        set => SetValue(CompletedCommandProperty, value);
    }

    public Entry() : base()
    {
        Completed += Entry_Completed;
    }

    private void Entry_Completed(object sender, EventArgs e)
    {
        CompletedCommand?.Execute(CompletedCommandParameter);
    }
}

Googling "xamarin unsubscribe events" gave lots of interesting results.谷歌搜索“xamarin 取消订阅事件”给出了很多有趣的结果。 I feel like, if possible, you want to use an EventToCommandBehavior (part of xamarin toolkit i believe?) to avoid using events.我觉得,如果可能的话,您想使用 EventToCommandBehavior(我相信是 xamarin 工具包的一部分?)来避免使用事件。 But if you can't do that, unsubscribing might be unnecessary but still a best practice.但如果你不能这样做,取消订阅可能是不必要的,但仍然是最佳做法。

Source: https://github.com/xamarin/xamarin-forms-samples/issues/188来源: https://github.com/xamarin/xamarin-forms-samples/issues/188

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

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