简体   繁体   English

按钮命令绑定不起作用

[英]Button command binding doesn't work

I created a new UserContol with a button inside. 我创建了一个新的UserContol,里面有一个按钮。 Iwanted to bind the button command to a dependancy property of the new user control like this. 想要像这样将button命令绑定到新用户控件的依赖性属性。

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

this is the DP on the containing UserControl: 这是包含UserControl的DP:

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) 因为它与其他按钮属性的工作方式相同(例如, Visibility

It's possible that your binding is not working because there is nothing that says the Button1Command property is a member of your UserControl . 您的绑定可能无法正常工作,因为没有任何内容表明Button1Command属性是UserControl的成员。

You can confirm that this is the problem by looking in the Output window when debugging your program in Visual Studio. 在Visual Studio中调试程序时,可以通过在“输出”窗口中查看来确认这是问题所在。 You'll likely see binding errors that member Button1Command wasn't found. 您可能会看到未找到成员Button1Command绑定错误。

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). 通常的解决方法是在UserControl的根元素中添加名称属性,例如x:Name="root" (您可以选择自己的名称,或者使用已有的名称)。 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. 您需要类实现ICommand接口。

     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; 在DataContext(MVVM ... ect。)中定义命令。别记得设置DataContext ...,例如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 ... 而已 ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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