Button
、Entry
、Label
、Picker
等 View 可以有一个 x :Name
属性。
<Label x:Name="myLabelName" Text="Some text" />
x
定义为 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
。
现在我想处理未分类的项目,因此我使用 object
作为类型。
如何从 object
的代码中获取字符串形式的 x:Name
属性?我现阶段不知道类型。
编辑:
为了让事情更清楚,我想发布一些代码。我有一个像这样的普通 XAML 页面:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="XamlSamples.HelloXamlPage">
<Label x:Name="myLabelName" Text="Some text" />
</ContentPage>
在代码隐藏文件中,如果我执行 nameof(this.myLabelName)
,我可以获得 x:Name
属性。但是,如果您只有 object
,这是如何完成的呢?
public partial class HelloXamlPage
{
public HelloXamlPage()
{
InitializeComponent();
List<string> itemsWhichPassTheCheck = this.Check(new List<object>() { this.myLabelName });
}
}
private List<string> Check(List<object> itemList)
{
// do some check here ...
// here I have only object and I want to get the x:Name attribute thereof
}
最佳答案
我 100% 确定有一种方法可以重构您的代码以避免您的需求,但为了回答问题,这里是您获取任何对象名称的方法:
我们确信任何用 x:Name
标记的对象都会创建一个同名的字段。
因此,使用反射,您应该能够获取页面中定义的所有字段,将它们与您的对象进行比较,如果匹配则返回字段名称。
我还没有测试过这个,但是应该可以,或者至少让你走上正轨
string GetNameOf(object topLevelXaml, object reference)
{
var fields = topLevelXaml.GetType().GetFields();
foreach (var fi in fields) {
var value = fi.GetValue(topLevelXaml);
if (value != reference)
continue;
return fi.Name;
}
return null;
}
但同样,您可能根本不需要这个。
关于c# - 如何从对象中获取 Xamarin.Forms 元素的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40932979/