简体   繁体   中英

MVVM Events and ICommand Binding

I have Custom Control and it handles an event from a control and throws it to is parent.

Control Code

public delegate void ThumbMovedEventHandler(object sender);
public event ThumbMovedEventHandler ThumbMoved;

private void SliderTimeLine_OnDragCompleted(object sender, DragCompletedEventArgs e)
{
     if (ThumbMoved != null)
            ThumbMoved(this);
}

I want to bind the event to a command in my MVVM application.

View Code

    <TimeTimeSlider:TimeSlider 
                   StartDate="{Binding TimeLineStartDate}"
                   local:CommandBehavior.Event="ThumbMoved"
                   local:CommandBehavior.Action="{Binding ThumbMoved}"
                   local:CommandBehavior.CommandParameter="Thumb Place Ment Moved "
                                   />

ViewModel Code

    private ICommand thumbMoverCommand;

   public ICommand ThumbMoved
    {
        get { return this.thumbMoverCommand ?? (this.thumbMoverCommand = new DelegateCommand(this.ExcuteThumbMoved)); }
    }


    public void ExcuteThumbMoved()
    {
      //Do Something;
    }

When The Event is thrown from the control on a Class Called CommandBehaviorBinding

   public ICommand Command
    {
        get { return _command; }
        set
        {
            _command = value;
            //set the execution strategy to execute the command
            _strategy = new CommandExecutionStrategy { Behavior = this };
        }
    }

    public void Execute()
    {
        _strategy.Execute(CommandParameter);
    }

I get a "Object reference not set to an instance of an object" error because _strategy is null.

How do i fix this?

local:CommandBehavior. Command ="{Binding ThumbMoved}"

     <TimeTimeSlider:TimeSlider 
               StartDate="{Binding TimeLineStartDate}"
               local:CommandBehavior.Event="ThumbMoved"
               local:CommandBehavior.Command="{Binding ThumbMoved}"
               local:CommandBehavior.CommandParameter="Thumb Place Ment Moved "
                               /> 

You need to do your _strategy assignment somewhere else. Either in constructor, when another command occurs, an event occurs, etc -- wherever Behavior is not null, such as when instantiated or when changed/updated. Right now, it is never being set in that setter - can be seen by putting a breakpoint in that setter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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