How to implement IsEnabledChanged of silverlight dataform using MVVM

北战南征 提交于 2019-12-02 08:35:21

I created a Behavior that does something similar with EditStarted event of a data form.

public class EditableDataFormBehavior : Behavior<RadDataForm>
{
    protected override void OnAttached()
    {
        base.OnAttached();

        AssociatedObject.Loaded += AssociatedObject_Loaded;
    }

    void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
    {
        AssociatedObject.CurrentItemChanged += AssociatedObject_CurrentItemChanged;
    }

    void AssociatedObject_CurrentItemChanged(object sender, EventArgs e)
    {
        var editableObject = AssociatedObject.CurrentItem as INotifyEditableObject;
        if (editableObject != null)
        {
            editableObject.EditStarted += Object_EditStarted;
        }
    }

    void Object_EditStarted(object sender, EventArgs e)
    {
        AssociatedObject.BeginEdit();
    }

    protected override void OnDetaching()
    {
        // detach the event handler
        AssociatedObject.Loaded -= AssociatedObject_Loaded;
        AssociatedObject.CurrentItemChanged -= AssociatedObject_CurrentItemChanged;

        var editableObject = AssociatedObject.DataContext as INotifyEditableObject;
        if(editableObject!=null)
            editableObject.EditStarted -= Object_EditStarted;
        base.OnDetaching();
    }


}

You would just need to modify slightly by attaching to the IsEnabledChanged event instead. You are trying to achieve a view only behavior and the viewmodel should know nothing about it. Main benefit doing it this way is that it is more reusable than code behind.

In the event handler you would add your code:

    if (!IsEnabled)
    {
        VisualStateManager.GoToState(DataForm, "Disabled", true);
    }
    else
    {
        VisualStateManager.GoToState(DataForm, "Normal", true);
    }

Attach the behavior to the data form (mine was made for telerik's one but should be doable with the sdk)

 <i:Interaction.Behaviors>
                <utilities:EditableDataFormBehavior/>
 </i:Interaction.Behaviors>

EventTrigger only deals with routed events (see documentation). As you dealing with a dependency property changed event the EventTrigger simply does not recognize it.

So from what I can see using code behind is the only way of achieving the functionality you require. Also you are dealing with a functionality that belongs to the view and is bound to the control you are using (the DataForm in this case). Therefore, it would be contra-productive to pull that dependency into the view model, as the view model should be independent form any given implementation of the view - i.e. the goal is to design your view model so that it can be used independent from the view and the controls uesed therein.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!