简体   繁体   中英

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM