我有2个Usercontrols,父母和孩子,子控件有按钮女巫我想用父viewmodel方法点击,但它不起作用,请告诉我我错过了什么 在父视图中,我有这样的事情:
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);
}
VM父命令:
public ICommand ExampleCommand
{
get
{
if (this.exampleCommand == null)
{
this.exampleCommand = new DelegateCommand(...);
}
return this.exampleCommand ;
}
}
答案 0 :(得分:1)
我不确定我是否理解你,但如果您正在寻找一种方法在您的子用户控件上执行命令,当您单击父用户控件中的按钮时,您需要执行以下操作:
如何从父usercontrol对子usercontrol执行命令..如果你想要它反过来你只需要用parent替换每个子单词,并用子表示每个父单词:)