Reputation: 124
I have a MainWindow in my application. Within the MainWindow I dynamically host a user control (ucA). Within ucA i have another user control (ucB).
When I click the save button on ucB, i need to execute a routine on ucA.
How can I reference the routine on ucA?
Upvotes: 2
Views: 790
Reputation: 364
Here are some ways I can think of :-
You can use CallMethodAction
in your xaml to call a method of parent usercontrol. The code goes like this :-
<UserControl x:Class="WpfApplication.ucB"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
Height="300" Width="300">
<StackPanel>
<Button Content="Save" x:Name="SaveButton" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<ei:CallMethodAction TargetObject="{Binding RelativeSource={RelativeSource FindAncestor, AncestorLevel=2, AncestorType=UserControl}}"
MethodName="MethodToCallOnucA" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
</StackPanel>
This way you can call the method on ucA which is the parent of ucB. BUT there is a big limitation to this way of calling methods from xaml. The limitation is that in this case your `MethodToCallOnucA' must return void and must have no method parameters.
If you must send parameters to your method then you need to follow the SECOND approach over here. For this we need to use Commands to make a call to method of Usercontrol. You need to change the button's code in the xaml above like this :-
<Button Content="Save" x:Name="SaveButton" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<i:InvokeCommandAction Command="{Binding RelativeSource={RelativeSource FindAncestor,AncestorLevel=2, AncestorType=UserControl}, Path=DoActionCommand}" CommandParameter="ValueToSendAsMethodParameter" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
Here DoActionCommand is a ICommand property defined in your usercontrol ucA and this ICommand points to the method you need to call in ucA.
Upvotes: 1