我有 2 个用户控件,父和子,子控件有按钮女巫我想用父视图模型方法单击,但它不起作用,请告诉我我在父视图中错过了什么,我有这样的东西:
XAML
...
<view:childUC vm:ChildBehaviuor.AddCommand="{Binding ExampleCommand}"/>
行为代码:
public static readonly DependencyProperty AddCommandProperty =DependencyProperty.RegisterAttached
(
"AddCommand",
typeof(ICommand),
typeof(childBehavior),
new PropertyMetadata(OnAddCommand)
);
public static ICommand GetAddCommand(DependencyObject obj)
{
return (ICommand)obj.GetValue(AddCommandProperty);
}
public static void SetAddCommand(DependencyObject obj, ICommand value)
{
obj.SetValue(AddCommandProperty,value);
}
private static ICommand command;
private static void OnAddCommand(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
child gp = sender as child;
childBehavior.command = (ICommand)sender.GetValue(childBehavior.AddCommandProperty);
if(gp != null && command != null)
{
if ((e.NewValue != null) && (e.OldValue == null))
{
gp.AddButton.Click += ButtonClick;
}
else if ((e.NewValue == null) && (e.OldValue != null))
{
gp.AddButton.Click -= ButtonClick;
}
}
}
public static void ButtonClick(object sender,RoutedEventArgs eventArgs)
{
childBehavior.command.Execute(null);
}
虚拟机父命令:
public ICommand ExampleCommand
{
get
{
if (this.exampleCommand == null)
{
this.exampleCommand = new DelegateCommand(...);
}
return this.exampleCommand ;
}
}