Xamarin XAML x:Static reference to property in a nested class

限于喜欢 提交于 2021-01-28 14:22:55

问题


I'm writing a mobile app using Xamarin and I have a static class called Strings that wraps my RESX resources. I want to use x:Static to bind to these in my XAML files. This is working if I have a single static class with static properties to bind to.

I'm cutting out some comments and other non-essential bits, but it basically looks like this:

namespace MyCompany.Resources
{
    public static partial class Strings
    {
        public static string LabelUsername { get { return Resources.LabelUsername; } }
    }
}

Then in my XAML, I bind to it like this:

<Entry Placeholder="{x:Static resources:Strings.LabelUsername}"

where resources is defined as

xmlns:resources="clr-namespace:MyCompany.Resources;assembly=MyCompany"

That all works fine. It breaks down when I add a nested class to Strings. The class looks like this:

namespace MyCompany.Resources
{
    public static partial class Strings
    {
        public static partial class Label
        {
            public static string Username { get { return Resources.Label_Username; } }
        }
    }
}

If I do that, then I would bind to it in my XAML like this:

<Entry Placeholder="{x:Static resources:Strings.Label.Username}"

Notice how after "resources:" we now have three levels (Strings.Label.Username). This seems to be what fails. When I do this, I get the compile error: Type Strings.Label not found in xmlns clr-namespace:MyCompany.Resources;assembly=MyCompany

Also, I can access the nested class and its properties just fine from my ViewModels. Is there any way to make this work from the XAML? I know I could bind to a variable in the VM and then have that reference Strings.Label.Username, but I don't want to do that for every resource binding.


回答1:


Your static property's name in the binding should be

Strings+LabelUsername.Username

Not only did you have a typo, but you tried to use the dot notation to reference the nested class, which won't work.

Bindings use standard .net reflection notation for referencing properties and classes by name (they either use a parser on the string or use reflection directly, can't be arsed to check the codebase). Nested class names use a + to separate the containing class name and the inner class name. You can read more about that here:

C# : having a "+" in the class name?



来源:https://stackoverflow.com/questions/48080481/xamarin-xaml-xstatic-reference-to-property-in-a-nested-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!