Reputation: 1
I have a UserControl where i override some event like this:
public class MyControl: UserControl
{
protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
{
base.OnMouseLeftButtonUp(e);
// handle mouse event up
}
}
I add this control to antother UserControl -> Grid, this Grid has MouseUp registered.
public class MyParent: UserControl
{
private void Grid_MouseUp(object sender, MouseButtonEventArgs e)
{
// handle grid mouse event
}
}
And in MyParent XAML i have simply:
<UserControl ... >
<Grid Name="Grid" MouseUp="Grid_MouseUp">
<my:MyControl Height="250" Width="310" Visibility="Visible" Opacity="1" IsEnabled="True" />
</Grid>
</UserControl>
What i notice is that when i release mouse over MyControl the event is captured by Grid and not routed to MyControl, why?
How can i receive MouseUp event inside MyControl class?
EDIT With MouseDown all works as expected, only MouseUp not works... and both event are registered for parent Grid too, so what is the difference?
EDIT2
Ok, i think i found the problem, if i add MyControl to MyParent -> Grid directly in XAML, all works good, but if i add it programmatically "MyParentInstance.Grid.Children.Add(MyControlInstance)" then i have the problem above.
Is my code to add control correct?
Thanks.
Upvotes: 0
Views: 1893
Reputation: 1
I did not come across the answer to this question after an extensive search of forums so I'm providing my solution here although this post is dated. I made use of event handlers that I'd already built in the child control by making them public. When the ChildControl user control is added to the Window at the top level, these fire. When nested within parent, the event had to be handled at the parent level.
When programmatically adding a control, add the event handler in the Parent control, such as:
class Parent : UIElement
{
//...
void Parent_AddChildControl()
{
ChildControl child = new ChildControl();
child.MouseEnter += child_MouseEnter;
UiElementX.Children.Add(child);
}
void child_MouseEnter( object sender , MouseEventArgs e )
{
((ChildControl)sender).ChildControl_MouseEnter(sender, e);
}
}
class ChildControl : UIElement
{
//...
public void ChildControl_MouseEnter(object sender, MouseEventArgs e)
{
//event handling
}
}
Upvotes: 0
Reputation: 2582
RoutedEvent
s only work for the parents of the element, which is invoking the specific event. That means for you, that all parent controls of your grid will receive the event, but children will not. For more information about routed events see Routed Events Overview. To solve your problem I would suggest to register the MouseUp
Event at MyControl:
<UserControl ... >
<Grid Name="Grid">
<my:MyControl MouseUp="Grid_MouseUp" Height="250" Width="310" Visibility="Visible" Opacity="1" IsEnabled="True" />
</Grid>
</UserControl>
Upvotes: 0