Get x:Name of control by clicking

Asked

Viewed 39 times

0

Hello, I have a stackpanel with a sequence of Abels and would like to capture the x:Name of the controller in the Label Mouseup event.

XAML:

    <StackPanel Background="#FF405089" HorizontalAlignment="Left" Width="200" Margin="0,0,0,243" MouseUp="StackPanel_MouseUp">
        <Label x:Name="BtnLabelUm" HorizontalAlignment="Left" VerticalAlignment="Top" Foreground="#FFD3E556" Width="200" Padding="5">
            <Label.Content>
                <Grid Width="190">
                    <Image Margin="24,0,142,0" Source="_Data/_Media/_Img/internet.png" UseLayoutRounding="True" SnapsToDevicePixels="True"/>
                    <Label Content="Home" Foreground="#FFD3E556" Margin="84,0,0,0" FontSize="18"/>
                </Grid>
            </Label.Content>
        </Label>
        <Label x:Name="BtnLabelDois" HorizontalAlignment="Left" VerticalAlignment="Top" Foreground="#FFD3E556" Width="200" Padding="5">
            <Grid Width="190">
                <Image Margin="24,0,142,0" Source="_Data/_Media/_Img/commerce-and-shopping.png" UseLayoutRounding="True" SnapsToDevicePixels="True"/>
                <Label Content="Calculator" Foreground="#FFD3E556" Margin="84,0,0,0" FontSize="18"/>
            </Grid>
        </Label>
    </StackPanel>

C#:

    private void StackPanel_MouseUp(object sender, MouseButtonEventArgs e)
    {
        textbox1.Text = ""; // aqui entra o nome do elemento clicado, por exemplo BtnLabelUm.Name
    }

The intention is to use the element name to call another method depending on the label clicked.

1 answer

0


Looking at Stackoverflow(American community) I found an answer, a method that gets the name of the element and checks its type, returning its name.

C#

    public static string ObterNome(object sender)
    {
        // primeiro checar se é um FrameworkElement
        var element = sender as FrameworkElement;
        if (element != null)
            return element.Name;
        // se não, tentar obter o nome da propriedade.
        try { return (string)sender.GetType().GetProperty("Name").GetValue(sender, null); }
        catch
        {
            // por ultimo, tentar obter o valor do campo Name.
            try { return (string)sender.GetType().GetField("Name").GetValue(sender); }
            catch { return null; }
        }
    }

Source: https://stackoverflow.com/questions/3066247/how-can-i-get-the-xname-of-an-object-from-code

Browser other questions tagged

You are not signed in. Login or sign up in order to post.