Juan Pablo Gomez
Juan Pablo Gomez

Reputation: 5534

Get a reference to an object with his name c#

I Have a wpf UserControl with some shapes into it like this.

<UserControl>
    <Grid Name="Contenedor1" Height="299.814" Width="238.429" 
        <Path x:Name="_1_2" Data=""/>
        <Path x:Name="_1_3" Data=""/>
        <Path x:Name="_1_4" Data=""/>
        <Path x:Name="_1_5" Data=""/>
        <Path x:Name="_1_6" Data=""/>
        <Path x:Name="_1_7" Data=""/>
        <Path x:Name="_1_8" Data=""/>
    </Grid>
</UserControl>

I want in my code behind get a reference to one path by hisname, at one procces i get the number of the shape 1 2 3 ... n and formating it properly I get the corresponding object name, something like: if i get 3, the object name is _1_3.

Now I get the name, and need a reference to my shape to make it some changes. How can i do to get this reference at my code behind

Upvotes: 2

Views: 1067

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564851

You can use FrameworkElement.FindName to find the proper Path:

// In code behind
var element = 3; // You say you already have this
var name = "_1_" + element.ToString();

Path path = this.FindName(name) as Path;
if (path != null)
{
   // use path
}

Upvotes: 4

Related Questions