简体   繁体   English

如何从对象中获取 Xamarin.Forms 元素的名称?

[英]How to get the name of Xamarin.Forms element from object?

Views like Button , Entry , Label , Picker and so on can have a x:Name attribute. ButtonEntryLabelPicker等视图可以具有x:Name属性。

<Label x:Name="myLabelName" Text="Some text" />

x is defined as xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" . x定义为xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"

Now I want to work with unclassified items and therefore I use object as type.现在我想使用未分类的项目,因此我使用object作为类型。

How do I get the x:Name attribute as string in code from a object ?如何从object的代码中获取x:Name属性作为字符串? I don't know the type at this stage.我不知道现阶段的类型。

Edit:编辑:

To make things more clear I want to post some code.为了让事情更清楚,我想发布一些代码。 I have a normal XAML page like this:我有一个像这样的普通 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>

In the code-behind file I can get the x:Name attribute if I do nameof(this.myLabelName) .在代码隐藏文件中,如果我执行nameof(this.myLabelName) ,我可以获得x:Name属性。 But how is this done if you have object only?但是如果你只有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
}

I'm 100% sure there's a way to refactor your code to avoid the need you have, but for the sake of answering, here's how you could get the name of any objects:我 100% 确定有一种方法可以重构您的代码以避免您的需要,但为了回答,您可以通过以下方式获取任何对象的名称:

We know for sure that any object tagged with x:Name will create a field of the same name.我们确信任何用x:Name标记的对象都会创建一个同名字段。

So, using reflection, you should be able to get all the fields defined in your page, compare them against your object, and return the field name if it matches.因此,使用反射,您应该能够获取页面中定义的所有字段,将它们与您的对象进行比较,如果匹配则返回字段名称。

I haven't tested this, but that should work, or at least put you on the right track我还没有测试过这个,但这应该可以工作,或者至少让你走上正轨

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;
}

But again, you shouldn't probably need this at all.但同样,您可能根本不需要这个。

As a variant in .xaml use both with the same: x:Name="example" ClassID="example"作为 .xaml 中的变体,两者使用相同:x:Name="example" ClassID="example"

in .cs: Label gotNext = (Label)FindByName(gotLabel.ClassId)在 .cs 中:标签 gotNext = (Label)FindByName(gotLabel.ClassId)

in my situation example was: void Feature_Tapped(System.Object sender, System.EventArgs e)在我的情况下,示例是:void Feature_Tapped(System.Object sender, System.EventArgs e)

        Label gotLabel = sender as Label;
        Label gotNext = (Label)FindByName(gotLabel.ClassId+"a");

如何从列表中获取密钥<object>在 Firebase 在 Xamarin.Forms 中?<div id="text_translate"><p> I am programming in Xamarin.Forms, I am also using the FirebaseDatabase [dot] net Nuget I have the following method, in connection to my Firebase Realtime Database, which sends a List.</p><pre> public static async Task&lt;bool&gt; PostDetallePedido(List&lt;AgregarCarrito&gt; carrito) { try { var result = await firebase.Child("DetallePedidos").Child(Preferences.Get("idOrder", string.Empty)).PostAsync(carrito); result2 = result.Key; var keyTable = new KeyClass() { keyU = result2, orderId = Preferences.Get("idOrder", string.Empty) }; await firebase.Child("keyTable").Child(Preferences.Get("idOrder", string.Empty)).PostAsync(keyTable); return true; } catch (Exception e) { Debug.WriteLine($"Error:{e}"); return false; } }</pre><p> 我的数据库填充如下<a href="https://i.stack.imgur.com/pBxxr.png" rel="nofollow noreferrer">图1</a></p><p> 使用前面的代码,我可以获得唯一 ID,但我仍然不知道如何获取以自动增量方式生成的值</p><pre>-M7B6xMB19uodzf-C71H | -0 | -1</pre><p> <strong>编辑:</strong></p><pre> public static async Task&lt;List&lt;AgregarCarrito&gt;&gt; GetDetailByUser(int id) { try { var key = await GetKey(id); var value = (await firebase.Child("DetallePedidos").Child(Convert.ToString(id)).Child(key.keyU).OnceAsync&lt;AgregarCarrito&gt;()).Select(item =&gt; new AgregarCarrito { orderId = item.Object.orderId, ProductName = item.Object.ProductName, CustomerId = item.Object.CustomerId, Price = item.Object.Price, TotalAmount = item.Object.TotalAmount, ProductId = item.Object.ProductId, Qty = item.Object.Qty, imageUrl = item.Object.imageUrl, Valor = item.Object.Valor }).ToList(); return value; } catch (Exception e) { Debug.WriteLine($"Error:{e}"); return null; } }</pre><p> 我创建了一个使用 orderId 返回键值的方法,但我仍然无法访问列表的值,在这种情况下,这将是发送列表时以自动增量方式生成的对象</p><p><a href="https://i.stack.imgur.com/ENEas.png" rel="nofollow noreferrer">图 2</a></p></div></object> - How can I get a key from a List <object> in Firebase in Xamarin.Forms?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从Xamarin.Forms中的对象获取BaseType - Get BaseType from object in Xamarin.Forms Xamarin.forms:如何从 Listview 获取对象值 - Xamarin.forms: How to get Object value from a Listview 如何从列表中获取密钥<object>在 Firebase 在 Xamarin.Forms 中?<div id="text_translate"><p> I am programming in Xamarin.Forms, I am also using the FirebaseDatabase [dot] net Nuget I have the following method, in connection to my Firebase Realtime Database, which sends a List.</p><pre> public static async Task&lt;bool&gt; PostDetallePedido(List&lt;AgregarCarrito&gt; carrito) { try { var result = await firebase.Child("DetallePedidos").Child(Preferences.Get("idOrder", string.Empty)).PostAsync(carrito); result2 = result.Key; var keyTable = new KeyClass() { keyU = result2, orderId = Preferences.Get("idOrder", string.Empty) }; await firebase.Child("keyTable").Child(Preferences.Get("idOrder", string.Empty)).PostAsync(keyTable); return true; } catch (Exception e) { Debug.WriteLine($"Error:{e}"); return false; } }</pre><p> 我的数据库填充如下<a href="https://i.stack.imgur.com/pBxxr.png" rel="nofollow noreferrer">图1</a></p><p> 使用前面的代码,我可以获得唯一 ID,但我仍然不知道如何获取以自动增量方式生成的值</p><pre>-M7B6xMB19uodzf-C71H | -0 | -1</pre><p> <strong>编辑:</strong></p><pre> public static async Task&lt;List&lt;AgregarCarrito&gt;&gt; GetDetailByUser(int id) { try { var key = await GetKey(id); var value = (await firebase.Child("DetallePedidos").Child(Convert.ToString(id)).Child(key.keyU).OnceAsync&lt;AgregarCarrito&gt;()).Select(item =&gt; new AgregarCarrito { orderId = item.Object.orderId, ProductName = item.Object.ProductName, CustomerId = item.Object.CustomerId, Price = item.Object.Price, TotalAmount = item.Object.TotalAmount, ProductId = item.Object.ProductId, Qty = item.Object.Qty, imageUrl = item.Object.imageUrl, Valor = item.Object.Valor }).ToList(); return value; } catch (Exception e) { Debug.WriteLine($"Error:{e}"); return null; } }</pre><p> 我创建了一个使用 orderId 返回键值的方法,但我仍然无法访问列表的值,在这种情况下,这将是发送列表时以自动增量方式生成的对象</p><p><a href="https://i.stack.imgur.com/ENEas.png" rel="nofollow noreferrer">图 2</a></p></div></object> - How can I get a key from a List <object> in Firebase in Xamarin.Forms? 如何从 Xamarin.Forms 中的 UWP 访问 PCL 中的参数 - How to get access to the parameters in PCL from UWP in Xamarin.Forms 如何从 Xamarin.Forms 获得连续的地理定位? - How can I get a continous geolication from Xamarin.Forms? 如何从Xamarin.Forms中的流获取图像的路径 - How to get the path of the image from stream in Xamarin.Forms 如何在 xamarin.forms 中获取 ListView 的子项? - How to get children of the ListView in xamarin.forms? 如何在Xamarin.Forms中获取以前的数据 - How to get previous data in Xamarin.Forms 如何在Xamarin.forms上获取字节[]用于图像 - how to get byte[] for Image on Xamarin.forms 如何在 Xamarin.Forms 中获取连接的 SSID? - How to get the connected SSID in Xamarin.Forms?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM