首页 > 解决方案 > 使用 try catch 自定义 Xamarin.Forms.Command

问题描述

我已经复制了Xamarin.Forms.Command,并在 Execute 方法中添加了一个尝试捕获,当我的 InvalidAppVersionException 发生时发布特定事件(使用 EventAggregator de Prism)。

try catch 不起作用,我不明白为什么。任何人都可以帮助我吗?

我的自定义命令代码:

public class LudaAppCommand : ICommand
{
    readonly IEventAggregator _eventAggregator;
    readonly Func<object, bool> _canExecute;
    readonly Action<object> _execute;

    public LudaAppCommand(Action<object> execute, IEventAggregator eventAggregator)
    {
        if (execute == null)
            throw new ArgumentNullException(nameof(execute));

        _execute = execute;
        _eventAggregator = eventAggregator;
    }

    public LudaAppCommand(Action execute, IEventAggregator eventAggregator) : this(o => execute(), eventAggregator)
    {
        if (execute == null)
            throw new ArgumentNullException(nameof(execute));
    }

    public LudaAppCommand(Action<object> execute, Func<object, bool> canExecute, IEventAggregator eventAggregator) : this(execute, eventAggregator)
    {
        if (canExecute == null)
            throw new ArgumentNullException(nameof(canExecute));

        _canExecute = canExecute;
    }

    public LudaAppCommand(Action execute, Func<bool> canExecute, IEventAggregator eventAggregator) : this(o => execute(), o => canExecute(), eventAggregator)
    {
        if (execute == null)
            throw new ArgumentNullException(nameof(execute));
        if (canExecute == null)
            throw new ArgumentNullException(nameof(canExecute));
    }

    public bool CanExecute(object parameter)
    {
        if (_canExecute != null)
            return _canExecute(parameter);

        return true;
    }

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        // TODO: Este try catch no funciona :(
        try
        {
            _execute(parameter);
        }
        catch (Exceptions.InvalidAppVersionException)
        {
            _eventAggregator.GetEvent<Events.InvalidAppVersionEvent>().Publish();
        }
    }

    public void ChangeCanExecute()
    {
        EventHandler changed = CanExecuteChanged;
        changed?.Invoke(this, EventArgs.Empty);
    }
}

标签: xamarinxamarin.formscommandtry-catchprism

解决方案


推荐阅读