将事件转变为命令问题

时间:2020-08-18 08:13:20

标签: c# mvvm xamarin.forms

我正在尝试使用MVVM将Entry.Completed事件转换为Command。我找到了这篇文章: https://devblogs.microsoft.com/xamarin/turn-events-into-commands-behaviors/ 并尝试做类似的事情,但是在Bindable_Completed函数中的Behavior.cs文件中Command始终作为null传递,我不明白为什么,请帮助。 行为文件代码:

public class EntryCompletedBehavior : Behavior<Entry>
{
    protected override void OnAttachedTo(Entry bindable)
    {
        base.OnAttachedTo(bindable);

        AssociatedObject = bindable;

        bindable.BindingContextChanged += Bindable_BindingContextChanged;
        bindable.Completed += Bindable_Completed;
    }
    protected override void OnDetachingFrom(Entry bindable)
    {
        base.OnDetachingFrom(bindable);

        bindable.BindingContextChanged -= Bindable_BindingContextChanged;
        bindable.Completed -= Bindable_Completed;

        AssociatedObject = null;
    }

    private void Bindable_BindingContextChanged(object sender, System.EventArgs e)
    {
        OnBindingContextChanged();
    }
    private void Bindable_Completed(object sender, System.EventArgs e)
    {
        if (Command == null) return;

        //object parameter = Converter.Convert(e, typeof(object), null, null);
        if (Command.CanExecute(e))
        {
            Command.Execute(e);
        }

    }

    protected override void OnBindingContextChanged()
    {
        base.OnBindingContextChanged();
        BindingContext = AssociatedObject.BindingContext;
    }

    public Entry AssociatedObject { get; private set; }
    public static readonly BindableProperty CommandProperty =
            BindableProperty.Create("Command", typeof(ICommand), typeof(EntryCompletedBehavior), null);
    public ICommand Command
    {
        get { return (ICommand)GetValue(CommandProperty); }
        set { SetValue(CommandProperty, value); }
    }
}

Xaml代码:

    <Grid BindableLayout.ItemsSource="{Binding ActualValues}"
          Grid.Column="0"
          Grid.ColumnSpan="2"
          Grid.Row="0">
        <BindableLayout.ItemTemplate>
            <DataTemplate>
                <Frame Margin="{Binding Margin}">
                    <Entry TabIndex="{Binding Id}"
                           Text="{Binding Value}"
                           Placeholder="{Binding Placeholder}"
                           Style="{StaticResource EntryStyle}">
                        <Entry.Behaviors>
                            <behaviors:EntryCompletedBehavior Command="{Binding EntryCompletedCommand}"/> 
                        </Entry.Behaviors>
                    </Entry>
                </Frame>
            </DataTemplate>
        </BindableLayout.ItemTemplate>
    </Grid>

VM代码:

public SaveMeasurementViewModel()
        {
            SaveMeasurmentCommand = new Command(async () => await SaveMeasurment(), () => !IsBusy);
            ClearMeasurmentCommand = new Command(ClearMeasurment);
            EntryCompletedCommand = new Command(_ => EntryCompleted(_));

            ActualValues = new ObservableCollection<MyEntry>() { };
            for (int index = 0; index < numberOfMeasurments; index++)
            {
                RegisterObserver(new MyEntry(index, this));
            }
        }
  public System.Windows.Input.ICommand EntryCompletedCommand { get; protected set; }
    void EntryCompleted(object param)
    {
        Application.Current.MainPage.DisplayAlert("Save", "Measurment data has been saved", "OK");
    }

1 个答案:

答案 0 :(得分:0)

正如canton7所说,此问题是由于BindableLayout.ItemsSource引起的,我试图在整个VM类中而不是在指定的ItemSource中查找属性。 我在BindableLayout.ItemsSource外部检查了此命令绑定,并且工作正常。