Search code examples
wpfmvvmdata-bindingcommand

Can I execute command logic from different class in xaml


I have a common class DataGridRowCopyAction.

public class DataGridRowCopyAction
{
    public ICommand RowCopyCommand = new DelegateCommand(RowCopyAction)

    Private void RowCopyAction
    {
        // do something 
    }
}

Can I use RowCopyCommand as a common command inside multiple xamls I tried below method .But it is not working

xmlns:b="clr-namespace:x.y"
Command={Binging path=b:RowCopyCommand}

Command


Solution

  • If you have any non-View model class where you for example defined you Command like this:

     namespace YourNameSpace
     {
        public class YourCommand : ICommand
        {
            public bool CanExecute(object par)
            {
                // Define your logic
                return true;
            }
        
            public void Execute(object par)
            {
                // Define the action you want             
            }
        
            public event EventHandler 
    
    CanExecuteChanged;
            }    
          
    
    }
    

    You need to create an instance of the command logic class in your XAML or code-behind. For example, in your XAML:

    <Window x:Class="YourApp.MainWindow"
           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
           xmlns:local="clr-namespace:YourNameSpace">
        <Window.Resources>
            <local:YourCommand x:Key="YourCommand" />
        </Window.Resources>
    

    Finally, bindining and in your XAML controls, you can bind the Command property to the instance of your command logic class:

    <Button Content="Execute Command" Command="{StaticResource YourCommand}" />