Reputation: 43
I have 2 Usercontrols, parent and child, child control has button witch I want to click with parent viewmodel method, but it doesn't work, please tell me what I miss in parent view, I have something like this:
XAML
...
<view:childUC vm:ChildBehaviuor.AddCommand="{Binding ExampleCommand}"/>
Behavior code:
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 parent command:
public ICommand ExampleCommand
{
get
{
if (this.exampleCommand == null)
{
this.exampleCommand = new DelegateCommand(...);
}
return this.exampleCommand ;
}
}
Upvotes: 1
Views: 249
Reputation: 672
I am not sure if I understood you but if you are looking for a way to execute a command on your child usercontrol when you click a button in your parent usercontrol you need to do following:
Thats how you execute an command on child usercontrol from parent usercontrol.. if you want it the other way around you just have to replace every child word with parent, and every parent word with child :)
Upvotes: 1