首页 > 解决方案 > 是否可以将 XAML 中的类中的类中的常量引用为 ax:Static?

问题描述

在我的代码中,我有一个这样声明的常量:

namespace Test.AppService
{
    public static partial class Const
    {
        public static class Options
        {
            public const string PhraseVisible = "PV";
            public const string MeaningVisible = "MV";
            // Many more constants below here

我想在我的 XAML 中访问它,所以我输入了这个:

<ContentPage
    x:Class="Test.SettingsPage"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:app="clr-namespace:Test.AppService;assembly=Test">
    <Label Text="{x:Static app:Const.Options.PracticePhraseVisible}" />

当我将鼠标悬停在它上面时,IDE 向我显示它将应用程序识别为 Test.AppService.Const

我真的很困惑,不知道如何将文本设置为常量的值。谁能给我建议该怎么做?

这是我收到的该行的错误消息:

“无法解析类型“Const.Options”。(XFC0000)

标签: c#.netxamarinxamarin.forms

解决方案


您只需要使用Binding Source设置并从部分类Const中取出静态类Options,您可以将它放在同一个文件中但在部分类之外,并在XAML文件中像这样引用“app:Options.PracticePhraseVisible ”。

CS:

namespace Test.AppService
{
   public static partial class Const
  {
  }

  public static class Options
  {
        public const string PhraseVisible = "PV";
        public const string MeaningVisible = "MV";
        // Many more constants below here
  }
}

XAML:

<ContentPage
    x:Class="Test.SettingsPage"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:app="clr-namespace:Test.AppService;assembly=Test">
    <Label Text="{Binding Source={x:Static app:Options.PracticePhraseVisible}}" />
</ContentPage>

推荐阅读