rem*_*rem 2 c# string wpf types object
在WPF应用程序中,我有从自定义控件派生的对象:
...
<MyNamespace:MyCustControl x:Name="x4y3" />
<MyNamespace:MyCustControl x:Name="x4y4" />
...
Run Code Online (Sandbox Code Playgroud)
我可以使用名称引用这些对象:
x4y4.IsSelected = true;
Run Code Online (Sandbox Code Playgroud)
这样的功能也很好:
public void StControls(MyCustControl sname)
{
...
sname.IsSelected = true;
...
}
....
StControls(x4y3);
Run Code Online (Sandbox Code Playgroud)
但是我想在调用这个方法时使用一个字符串来引用一个对象.像这样(但这不起作用):
MyCustControl sc = new MyCustControl();
string strSc = "x1y10";
sc.Name = strSc;
StControls(sc); // nothing's happening
Run Code Online (Sandbox Code Playgroud)
这种方式甚至不编译:
MyCustControl sc = new MyCustControl();
string strSc = "x1y10";
sc = (MyCustControl) strSc; // Cannot convert type string to MyCustControl
StControls(sc);
Run Code Online (Sandbox Code Playgroud)
如何使用string变量来操作对象(即将其转换为对象)?
使用FindName: -
MyCustControl sc = (MyCustControl)this.FindName("x1y10");
Run Code Online (Sandbox Code Playgroud)
在XAML中使用x:Name时,将在与cs后面的代码中的类匹配的分部类中创建具有指定名称的字段.这个partial类是找到InitialiseComponent的实现的地方.在执行此方法期间,将找到具有该名称的对象并将其分配给该字段,FindName用于执行此操作.
当您有一个包含这样名称的字符串时,您可以简单地调用FindName自己,然后将返回的对象强制转换为自定义控件类型.
这实际上不是强制转换。您需要按名称查找控件的对象引用,可以通过以下方式完成:
MyCustControl control = (MyCustControl)frameworkElement.FindName("x4y3");
Run Code Online (Sandbox Code Playgroud)
frameworkElement包含的窗口(或任何网格等面板)在哪里。从窗口后面的代码中,this应该可以使用:)
如果您打算动态创建控件,请参阅此问题,您的命名方案似乎向我建议了这一点。但是,如果是这种情况,FindName则根本没有必要。您将在创建它们时将对所有已创建控件的引用存储在二维数组中。
int[,] controls = new int[10, 10];
for (int x = 0; x < 10; x++)
{
for (int y = 0; y < 10; y++)
{
// Create new control and initialize it by whatever means
MyCustControl control = new MyCustControl();
// Add new control to the container
Children.Add(control);
// Store control reference in the array
controls[x, y] = control;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以像下面这样访问控件:
controls[4, 3].IsSelected = true;
Run Code Online (Sandbox Code Playgroud)