使用Xamarin表单,在应用程序中使用x:Key=内部的x:Static,xaml不工作

nzk0hqpo  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(98)

因此,我正在编写一个Xamarin Forms应用程序,并试图消除整个应用程序中的任何魔术字符串。似乎总是以硬编码字符串结束的地方之一是App.Xaml文件,特别是其中任何内容的x:Key属性。
例如,对于条目:<Color x:Key="GrayColor">#8f8e8e</Color>字符串“GrayColor”是硬编码的,必须在使用它的任何位置准确键入。
我的想法是创建一个全局Constants类并在其中存储键。类似于:

public static class Constants
{
    public const string GrayColor = "GrayColor";
}

这适用于在对象的程式码后置中设定属性时存取色彩,例如:BackgroundColor = (Color)Application.Current.Resources[Constants.GrayColor],并在视图的Xaml中显示如下内容:TextColor="{StaticResource Key={x:Static helpers:Constants.GrayColor}}" .
然而,当我尝试使用<Color x:Key="{x:Static helpers:Constants.GrayColor}">#8f8e8e</Color>更新App.Xaml条目时,我一启动应用程序就收到错误System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidCastException: Specified cast is not valid.
我做了一些调查,我不知道是否支持在x:Key中使用x:Static。有人能给我指出正确的方向吗?我的完整代码如下所示:
App.Xaml类:

<Application x:Class="Test.Shared.App"
         xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"             
         xmlns:helpers="clr-namespace:Test.Shared.Helpers"
         xmlns:mvx="clr-namespace:MvvmCross.Forms.Bindings;assembly=MvvmCross.Forms">
<Application.Resources>
    <ResourceDictionary>           
        <Color x:Key="{x:Static helpers:Constants.GrayColor}">#8f8e8e</Color>            
    </ResourceDictionary>
</Application.Resources>

常量类:

namespace Test.Shared.Helpers
{
    /// <summary>
    /// Contains constants that are used throughout the app.
    /// </summary>
    public static class Constants
    {        
        public const string GrayColor = "GrayColor";        
    }
}

以及使用它的视图:

<?xml version="1.0" encoding="UTF-8" ?>
<Grid x:Class="Test.Shared.Controls.CustomView"
      xmlns="http://xamarin.com/schemas/2014/forms"
      xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
      xmlns:helpers="clr-namespace:Test.Shared.Helpers"
      x:Name="This">

<Grid.ColumnDefinitions>
    <ColumnDefinition Width=".15*" />
    <ColumnDefinition Width=".7*" />
    <ColumnDefinition Width=".15*" />
</Grid.ColumnDefinitions>

<StackLayout Grid.Row="0"
             Grid.Column="1"
             HorizontalOptions="CenterAndExpand"
             Spacing="15"
             VerticalOptions="CenterAndExpand">
    <Image Source="{Binding Source={x:Reference This}, Path=DisplayImageSource}" />
    <Label FontSize="14.5"
           HorizontalTextAlignment="Center"
           Text="{Binding Source={x:Reference This}, Path=DisplayText}"
           TextColor="{StaticResource Key={x:Static helpers:Constants.GrayColor}}" />
</StackLayout>
0dxa2lsx

0dxa2lsx1#

看起来x:Key只接受字符串。它不支持标记扩展。但是,您仍然可以摆脱魔术字符串。将颜色资源从App.xaml.cs的代码后面添加到资源字典中,如下所示:

Resources.Add(Constants.GrayColor, Color.FromHex("#8f8e8e"));

相关问题