Search code examples
wpfuielement

How to find clicked UIElement child


I would like to get the clicked UIElement's child element that is button. Maybe there is simple and short solution for this? I have searched for this answer awhile, but could't find solution that would be easy to understand and use. I will appreciate any kind of help related to this question.

Code that i have right now:

private new void MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{

    if (sender == (sender as UIElement))
    {

        //TODO: getting controls name that is placed inside clicked UIElement

    }

}

Edit:

Wanted to mention that UIElement is ContentControl that is using ResourceDictionary template. My xaml code looks something like this

 <ContentControl Style="{StaticResource DesignerItemStyle}">
        <Button x:Name="btnAdd" Content="add function" IsHitTestVisible="True" 
        HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
</ContentControl>

Solution

  • There are two properties in MouseButtonEventArgs which you can leverage for this purpose

    Source

    This property contains reference to the object that raised the event. example Button etc

    OriginalSource

    the original reporting source as determined by pure hit testing, before any possible Source adjustment by a parent class, which may have been done to flatten composited element trees. example a Rectangle, Border or any template element inside the Button.

    you can retrieve the Name for the element by casting OriginalSource to FrameworkElement or more appropriate

    if the OriginalSource is not the desired element then you can retrieve the Logical parent of OriginalSource and that is more likely to be the desired element and retrieving Name remain same as above.

    retrieve logical parent example

    LogicalTreeHelper.GetParent(e.OriginalSource as DependencyObject);