RelayCommand from lambda with constructor parameters

前端 未结 2 772
遇见更好的自我
遇见更好的自我 2021-01-19 18:23

If, in a XAML file, I bind a Button to \"Command\" from the following class, then clicking the Button does not cause DoIt to be executed:

class Thing()
{
  p         


        
2条回答
  •  时光取名叫无心
    2021-01-19 18:56

    your Problem is that calling the Method DoIt is inside another anonymous Method created by the lamda expression. Your expression

    () => DoIt(p1);
    

    creates a anonymous Method without parameters (seen as there are no variables provided in the first braces).

    I would recommend you to use the generic constructor from mvvm-light for creating the Command:

    class Thing
    {
        public Thing()
        {
           Command = new GalaSoft.MvvmLight.Command.RelayCommand(DoIt);
        }
    
        private void DoIt(bool p)
        {
           p.DoSomething(p);
        }
    
        public System.Windows.Input.ICommand Command { get; private set; }
    }
    

    Then just bind the Button to the "Command".

提交回复
热议问题