How to Bind Wpf Button to a Command in Viewmodelbase

How to bind WPF button to a command in ViewModelBase?

 <Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="wefwfwef"/>
</Grid>

the code behind for the window:

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModelBase();
}
}

The ViewModel:

public class ViewModelBase
{
private ICommand _clickCommand;
public ICommand ClickCommand
{
get
{
return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), ()=> CanExecute));
}
}
public bool CanExecute
{
get
{
// check if executing is allowed, i.e., validate, check if a process is running, etc.
return true/false;
}
}

public void MyAction()
{

}
}

Command Handler:

 public class CommandHandler : ICommand
{
private Action _action;
private Func<bool> _canExecute;

/// <summary>
/// Creates instance of the command handler
/// </summary>
/// <param name="action">Action to be executed by the command</param>
/// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
public CommandHandler(Action action, Func<bool> canExecute)
{
_action = action;
_canExecute = canExecute;
}

/// <summary>
/// Wires CanExecuteChanged event
/// </summary>
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}

/// <summary>
/// Forcess checking if execute is allowed
/// </summary>
/// <param name="parameter"></param>
/// <returns></returns>
public bool CanExecute(object parameter)
{
return _canExecute.Invoke();
}

public void Execute(object parameter)
{
_action();
}
}

I hope this will give you the idea.

Bind command in WPF using MVVM

You can bind the Command property of the button to any property that returns ICommand. Prism implements a nice convenient command called DelegateCommand that is very easy to use (here is a knock-off of it):

public ICommand MyButtonClickCommand 
{
get { return new DelegateCommand<object>(FuncToCall, FuncToEvaluate); }
}

private void FuncToCall(object context)
{
//this is called when the button is clicked
}

private bool FuncToEvaluate(object context)
{
//this is called to evaluate whether FuncToCall can be called
//for example you can return true or false based on some validation logic
return true;
}



<Button x:Name="myButton" Command="{Binding MyButtonClickCommand}" />

The CodeProject example How to use Commands in WPF has a very similar example with code that you can easily work through. The previous Stack Overflow question has an example using RoutedCommands that are statically bound to: How to bind Close command to a button, and How to bind WPF button to a command in ViewModelBase? has a slightly more advanced example.

How to execute command on button in WPF?

Your button need to have been different bind, beacuse inside the list-template you do not have access to global DataContext only to local. You need to use relative source to access global DataContext.

Command="{Binding Path=DataContext.AddNewTimesheetEntryCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Page}}}"

How to bind command to button in WPF using Prism framework

<Button 
Command="{Binding ChargeModuleDCommand}"
Content="Module A"
Background="Green"
FontWeight="Bold"
/>

If ModuleAViewModel is the Button's DataContext, that should work.

programmatically bind button to double click command wpf

You can set InputBinding to your Button to fire your command on double click

var newSequence = new Button
{
ToolTip = currentSequence,
Background = Brushes.Transparent,
BorderThickness = new Thickness(0),
HorizontalAlignment = HorizontalAlignment.Stretch,
HorizontalContentAlignment = HorizontalAlignment.Stretch,
Content = Path.GetFileName(currentSequence),
CommandParameter = currentSequence,
};

var mouseBinding = new MouseBinding();
mouseBinding.Gesture = new MouseGesture(MouseAction.LeftDoubleClick);
mouseBinding.Command = PlaylistLoadCommand;
newSequence.InputBindings.Add(mouseBinding);

How do I bind a command to a class above it?

private void LoadSecondVM()
{
ContentControlView = new SecondViewModel(LoadFirstVMCommand);
}
...

ctor of SecondViewModel:

public SecondViewModel(ICommand backCommand)
{
this.BackCommand = backCommand;
}

Binding Command to ViewModel inside UserControl

ButtonCommand must be a property for you to be able to bind to it:

public ICommand ButtonCommand { get; private set; }

You have defined it as a field:

public ICommand ButtonCommand;


Related Topics



Leave a reply



Submit