Reputation: 719
My question is very similiar to this: (Binding events to buttons in an ItemsControl) but I didn't found a solution there. I have an ItemsControl and inside its DataTemplate, I have another ItemsControl. The items in the outer control contain classes that have some properties, and one of the properties is a collection. The inner ItemsControl source is binded to this collection, and inside the inner controls DataTemplate there is a Button.
My problem is that when I wire up an event for the button (.. Click="dummyfunc") and try to run the project, I get an unhandled XamlParseException (4004) and says that "Failed to assign to property 'System.Windows.Controls.Primitives.ButtonBase.Click'" I declared my event handler in the CodeBehind of the page in which the outer ItemsControl is placed in the Xaml. And it works fine for the buttons placed in the outer controls DataTemplate. But in the inner controls template, I just cant wire up any events.
One thing works:
<HyperlinkButton Content="x">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<ei:CallMethodAction MethodName="DeleteMe" TargetObject="{Binding}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</HyperlinkButton>
But this triggers only a method (DeleteMe) which is implemented in the item I mentioned above, that has some properties and a collection.
But instead of this, I need to handle the events in the inner control with a usual method:
public void dummyfunc(object sender, RoutedEventArgs e){...}
(so i can get the button that fired the event for example:
sender as HyperinkButton
or
e.OriginalSource as HyperlinkButton
I suppose the problem is that the event is not bubbled up and I get the parse exception because the parser cannot find the event handler declaration in the actual scope, which apparently is not the CodeBehind for the inner control :(
The reason I need this, is because I would like to do some custom UI logic in code, and trigger the DeleteMe logic somehow only after this.
Thanks, Bálint
Upvotes: 4
Views: 1395
Reputation: 34240
It's not obvious from the spartan documentation for CallMethodAction
, but the method named by the MethodName
property can have either of these signatures:
void Method()
void Method(object associatedObject, object parameter)
Furthermore, the default parameter
for an EventTrigger
action is the event arguments value that would normally be passed as the second argument to an event handler. For the Click
event, the type of the parameter is RoutedEventArgs
so you can define your DeleteMe
method like this:
public void DeleteMe(object sender, RoutedEventArgs e)
{
Debug.WriteLine("sender: {0}", sender);
Debug.WriteLine("e.OriginalSource: {0}", e.OriginalSource);
}
This gives you access to all the information you desire when handling the Click
event.
Upvotes: 3