Xamarin EventToCommandBehavior不会连接AssociatedObject

时间:2017-10-18 12:38:10

标签: c# xamarin xamarin.forms

我在Xamarin,我正试图将一个事件哄骗到一个命令using the EventToCommandBehavior trick。我关注的示例代码是also described here。我遇到的问题是BehaviorBase' OnAttachedTo覆盖没有触发,这意味着事件连接不会发生。

如何触发这些命令?

第二个问题是,在出现此问题时,整个视图无法加载。如果我注释掉XAML,视图就可以了。也许这是一个线索?为什么整个视图不会因为这个而加载?我认为只有这种行为不会起作用,而不是整个观点。

My question is similar to this one, but the issue is different

现在了解详情:

我已经从示例中复制了两个类BehaviorBaseEventToCommandBehaviorThe code comes from here

我的观点

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="MyApp.Views.MyPage" xmlns:v="clr-namespace:MyApp.Views;assembly=MyApp" xmlns:b="clr-namespace:MyApp.Behaviors;assembly=MyApp" xmlns:c="clr-namespace:MyApp.Converters;assembly=MyApp">
    <ContentPage.Behaviors>
        <b:EventToCommandBehavior EventName="Disappearing" Command="{Binding DisappearingCommand}" />
        <b:EventToCommandBehavior EventName="Appearing" Command="{Binding AppearingCommand}" />
    </ContentPage.Behaviors>-->
    <ContentPage.Content>
        <StackLayout>
            <Entry Text="{Binding Name}"></Entry>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

在我的ViewModel中,我有AppearingCommandDisappearingCommand命令。 View的代码隐藏只有构造函数。

当我启动此页面时,OnEventNameChange会在EventToCommandBehavior中触发,但behavior.AssociatedObject为空,因此会退出。该变量为null,因为OnAttachedTo永远不会触发。为什么不?我做错了什么?

This Fires:

private static void OnEventNameChanged(BindableObject bindable, object oldValue, object newValue)
{
    var behavior = (EventToCommandBehavior)bindable;
    if (behavior.AssociatedObject == null)
    {
        return;
    }

    string oldEventName = (string)oldValue;
    string newEventName = (string)newValue;

    behavior.DeregisterEvent(oldEventName);
    behavior.RegisterEvent(newEventName);
}

但这绝不会:

protected override void OnAttachedTo(View bindable)
{
    base.OnAttachedTo(bindable);
    RegisterEvent(EventName);
}

base.OnAttachedTo是将behavior.AssociatedObject设置为某种内容的原因。这是它的副本:

protected override void OnAttachedTo(T bindable)
{
    base.OnAttachedTo(bindable);
    AssociatedObject = bindable;

    if (bindable.BindingContext != null)
    {
        BindingContext = bindable.BindingContext;
    }

    bindable.BindingContextChanged += OnBindingContextChanged;
}

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题。解决方案是将EventToCommandBehavior类的基类从BehaviorBase<View>更改为BehaviorBase<VisualElement>。因此应为以下内容:

public class EventToCommandBehavior : BehaviorBase<VisualElement>
{
    ...
}