In a WPF app I have objects, derived from a custom control:
...
<MyNamespace:MyCustControl x:Name="x4y3" />
<MyNamespace:MyCustControl x:Name="x4y4" />
...
I can reference these objects, using names:
x4y4.IsSelected = true;
Also such function works well:
public void StControls(MyCustControl sname)
{
...
sname.IsSelected = true;
...
}
....
StControls(x4y3);
But I want to use a string in order to reference an object when calling this method. Like this (but this isn’t working):
MyCustControl sc = new MyCustControl();
string strSc = "x1y10";
sc.Name = strSc;
StControls(sc); // nothing's happening
And this way even doesn’t compile:
MyCustControl sc = new MyCustControl();
string strSc = "x1y10";
sc = (MyCustControl) strSc; // Cannot convert type string to MyCustControl
StControls(sc);
How can I use string variable to manipulate with object (i.e. cast it to object)?
Use
FindName:-When you use x:Name in the XAML a field with the name specified is created in a partial class that matches the class in the code behind cs. This partial class is where the implementation of InitialiseComponent is found. During execution of this method the object with that name is found and assigned to the field, FindName is used to do this.
When you have a string contain such a name you can simply call
FindNameyourself and then cast the returned object to the custom control type.