我创建了一个新的 UserContol,里面有一个按钮。我想像这样将按钮命令绑定到新用户控件的依赖属性。
<Grid>
<Button Name="Button1" Command="{Binding Button1Command}" />
</Grid>
这是包含 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));
当我尝试使用它时,当我按下按钮时没有任何反应。它不识别命令。如果我添加一个事件,它会起作用。像这样:
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;
}
有没有办法在没有事件的情况下绑定它?因为它适用于我以相同方式执行的其他按钮属性(Visibility
例如)