简体   繁体   中英

Button command binding doesn't work

I created a new UserContol with a button inside. Iwanted to bind the button command to a dependancy property of the new user control like this.

<Grid>
 <Button Name="Button1" Command="{Binding Button1Command}" />
</Grid>

this is the DP on the containing UserControl:

public ICommand Button1Command
{
  get { return (ICommand)GetValue(Button1CommandProperty); }
  set { SetValue(Button1CommandProperty, value); }
}

public static readonly DependencyProperty Button1CommandProperty =
    DependencyProperty.Register("Button1Command", typeof(ICommand), typeof(BptCellTemplate), new FrameworkPropertyMetadata(null));

when i try to use it nothing happen when I press the button. It doesn't recognize the command. If I add an event it works. Like this:

 public static readonly DependencyProperty Button1CommandProperty =
    DependencyProperty.Register("Button1Command", typeof(ICommand), typeof(BptCellTemplate), new FrameworkPropertyMetadata(null, OnButton1CommandChanged));

private static void OnButton1CommandChanged(DependencyObject dependencyObject,
                                              DependencyPropertyChangedEventArgs args)
{
  var bptCellTemplate = dependencyObject as BptCellTemplate;
  if (bptCellTemplate == null || !(args.NewValue is ICommand))
  {
    return;
  }
  (bptCellTemplate.DataContext as BptCellTemplateViewModel).Button1Command = (ICommand)args.NewValue;

}

Is there a way to bind it without an event? because it works with other button properties that i did the same way ( Visibility for example)

It's possible that your binding is not working because there is nothing that says the Button1Command property is a member of your UserControl .

You can confirm that this is the problem by looking in the Output window when debugging your program in Visual Studio. You'll likely see binding errors that member Button1Command wasn't found.

The typical fix for this is to add a name attribute to your UserControl 's root element, such as x:Name="root" (you can choose your own name or use an existing one if you have it). Then, change your binding to the command to reference the new name:

<Button Name="Button1" Command="{Binding Button1Command, ElementName=root}" />
  1. You need class implements ICommand interface.

     public class RelayCommand : ICommand { #region Fields readonly Action<object> _execute; readonly Predicate<object> _canExecute; #endregion // Fields #region Constructors /// <summary> /// Creates a new command that can always execute. /// </summary> /// <param name="execute">The execution logic.</param> public RelayCommand(Action<object> execute) : this(execute, null) { } /// <summary> /// Creates a new command. /// </summary> /// <param name="execute">The execution logic.</param> /// <param name="canExecute">The execution status logic.</param> public RelayCommand(Action<object> execute, Predicate<object> canExecute) { if (execute == null) throw new ArgumentNullException("execute"); _execute = execute; _canExecute = canExecute; } #endregion // Constructors #region ICommand Members [DebuggerStepThrough] public bool CanExecute(object parameter) { return _canExecute == null ? true : _canExecute(parameter); } public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } public void Execute(object parameter) { _execute(parameter); } #endregion // ICommand Members } 
  2. Now there is binding very simple. Define Command in your DataContext (MVVM ...ect.) Don't remember setup DataContext ... for example DataContext = this; (this is your Window)

     RelayCommand _btnCommand; public ICommand Button1Command { get { if (_btnCommand == null) { _btnCommand = new RelayCommand(param => this.ExecuteButton1(), param => this.CanButton1()); } return _btnCommand; } } public void ExecuteButton1() { } public bool CanButton1() { return true; } 

That's it ...

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