StaticResource в MarkupExtension

В настоящее время я пытаюсь использовать статический ресурс с расширением для моей записи FontSize имущество. У меня есть этот кусок кода:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="PROJECT.Sources.Pages.Extras.EditProfilePage"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:control="clr-namespace:PROJECT.Sources.Controls;assembly=PROJECT"
    xmlns:extension="clr-namespace:PROJECT.Sources.Extensions;assembly=PROJECT"
    xmlns:sys="clr-namespace:System;assembly=mscorlib">

    <ContentPage.Resources>
        <ResourceDictionary>
            <Color x:Key="NL_BlueNight">#0E1728</Color>
            <Color x:Key="NL_OrangeBeer">#E87E07</Color>
            <Color x:Key="NL_OrangeSky">#BD4327</Color>
            <Color x:Key="NL_White">#ECECEC</Color>
            <sys:Double x:Key="EntryFontSize">20</sys:Double>
        </ResourceDictionary>
    </ContentPage.Resources>

    <ContentPage.Content>
        <AbsoluteLayout BackgroundColor="{x:StaticResource NL_BlueNight}">
            <AbsoluteLayout
                Margin="{Binding LayoutThicknessAdapter}"
                AbsoluteLayout.LayoutBounds="0.5, 0.5, 1, 1"
                AbsoluteLayout.LayoutFlags="All"
                BackgroundColor="Black">
                <control:Gif
                    AbsoluteLayout.LayoutBounds="0.5, 0, 1, 0.9"
                    AbsoluteLayout.LayoutFlags="All"
                    GifSource="Gifs/LoginBackground.gif" />
                <BoxView
                    AbsoluteLayout.LayoutBounds="0.5, 0.5, 1, 1"
                    AbsoluteLayout.LayoutFlags="All"
                    BackgroundColor="Transparent" />
            </AbsoluteLayout>

            <AbsoluteLayout
                Margin="{Binding LayoutThicknessAdapter}"
                AbsoluteLayout.LayoutBounds="0.5, 0.5, 1, 1"
                AbsoluteLayout.LayoutFlags="All"
                BackgroundColor="{StaticResource NL_BlueNight}"
                Opacity="0.8">
                <ScrollView AbsoluteLayout.LayoutBounds="0.5, 0, 1, 0.9" AbsoluteLayout.LayoutFlags="All">
                    <StackLayout
                        HorizontalOptions="Fill"
                        Orientation="Vertical"
                        Spacing="15"
                        VerticalOptions="CenterAndExpand">
                        <BoxView BackgroundColor="Transparent" HeightRequest="{Binding SeparatorHeight}" />
                        <control:CustomImageCircle
                            x:Name="UserProfileImageButton"
                            HeightRequest="{Binding PictureHeightWidth}"
                            HorizontalOptions="Center"
                            Source="{Binding CurrentUser.ImageProfile}"
                            VerticalOptions="Center"
                            WidthRequest="{Binding PictureHeightWidth}" />
                        <Image
                            HeightRequest="{Binding SeparatorHeight}"
                            HorizontalOptions="Center"
                            Source="{extension:ImageSource LogoPROJECT.png}" />
                        <AbsoluteLayout HeightRequest="{Binding EntryHeight}" WidthRequest="{Binding EntryWidth}">
                            <control:CustomEntry
                                AbsoluteLayout.LayoutBounds="0.5, 0.5, 1, 1"
                                AbsoluteLayout.LayoutFlags="All"
                                BackgroundColor="Transparent"
                                FontFamily="{extension:FontFamily Roboto_Light}"
                                FontSize="{extention:FontSize StaticResourceKey=EntryFontSize}}"
                                HasBorder="false"
                                Placeholder="pseudo"
                                PlaceholderColor="Gray"
                                Text="{Binding CurrentUser.Pseudo}"
                                TextColor="White"
                                XAlign="Center" />
                            <!--<BoxView
                                AbsoluteLayout.LayoutBounds="0.5, 0.7, 0.8, 1"
                                AbsoluteLayout.LayoutFlags="XProportional, YProportional, WidthProportional"
                                BackgroundColor="{StaticResource NL_OrangeBeer}" />-->
                        </AbsoluteLayout>
                        <AbsoluteLayout HeightRequest="{Binding EntryHeight}" WidthRequest="{Binding EntryWidth}">
                            <control:CustomEntry
                                AbsoluteLayout.LayoutBounds="0.5, 0.5, 1, 1"
                                AbsoluteLayout.LayoutFlags="All"
                                BackgroundColor="Transparent"
                                FontFamily="{extension:FontFamily Roboto_Light}"
                                FontSize="{extention:FontSize StaticResourceKey=EntryFontSize}}"
                                HasBorder="false"
                                Placeholder="email"
                                PlaceholderColor="Gray"
                                Text="{Binding CurrentUser.Email}"
                                TextColor="White"
                                XAlign="Center" />
                            <!--<BoxView
                                AbsoluteLayout.LayoutBounds="0.5, 0.7, 0.8, 1"
                                AbsoluteLayout.LayoutFlags="XProportional, YProportional, WidthProportional"
                                BackgroundColor="{StaticResource NL_OrangeBeer}" />-->
                        </AbsoluteLayout>
                        <AbsoluteLayout HeightRequest="{Binding EntryHeight}" WidthRequest="{Binding EntryWidth}">
                            <control:CustomEntry
                                AbsoluteLayout.LayoutBounds="0.5, 0.5, 1, 1"
                                AbsoluteLayout.LayoutFlags="All"
                                BackgroundColor="Transparent"
                                FontFamily="{extension:FontFamily Roboto_Light}"
                                FontSize="{extention:FontSize StaticResourceKey=EntryFontSize}}"
                                HasBorder="false"
                                Placeholder="firstname"
                                PlaceholderColor="Gray"
                                Text="{Binding CurrentUser.Firstname}"
                                TextColor="White"
                                XAlign="Center" />
                            <!--<BoxView
                                AbsoluteLayout.LayoutBounds="0.5, 0.7, 0.8, 1"
                                AbsoluteLayout.LayoutFlags="XProportional, YProportional, WidthProportional"
                                BackgroundColor="{StaticResource NL_OrangeBeer}" />-->
                        </AbsoluteLayout>
                        <AbsoluteLayout HeightRequest="{Binding EntryHeight}" WidthRequest="{Binding EntryWidth}">
                            <control:CustomEntry
                                AbsoluteLayout.LayoutBounds="0.5, 0.5, 1, 1"
                                AbsoluteLayout.LayoutFlags="All"
                                BackgroundColor="Transparent"
                                FontFamily="{extension:FontFamily Roboto_Light}"
                                FontSize="{extention:FontSize StaticResourceKey=EntryFontSize}}"
                                HasBorder="false"
                                Placeholder="lastname"
                                PlaceholderColor="Gray"
                                Text="{Binding CurrentUser.Lastname}"
                                TextColor="White"
                                XAlign="Center" />
                            <!--<BoxView
                                AbsoluteLayout.LayoutBounds="0.5, 0.7, 0.8, 1"
                                AbsoluteLayout.LayoutFlags="XProportional, YProportional, WidthProportional"
                                BackgroundColor="{StaticResource NL_OrangeBeer}" />-->
                        </AbsoluteLayout>
                        <AbsoluteLayout HeightRequest="{Binding EntryHeight}" WidthRequest="{Binding EntryWidth}">
                            <control:CustomEntry
                                AbsoluteLayout.LayoutBounds="0.5, 0.5, 1, 1"
                                AbsoluteLayout.LayoutFlags="All"
                                BackgroundColor="Transparent"
                                FontFamily="{extension:FontFamily Roboto_Light}"
                                FontSize="{extention:FontSize StaticResourceKey=EntryFontSize}}"
                                HasBorder="false"
                                Keyboard="Telephone"
                                Placeholder="phone number"
                                PlaceholderColor="Gray"
                                Text="{Binding CurrentUser.Number}"
                                TextColor="White"
                                XAlign="Center" />
                            <!--<BoxView
                                AbsoluteLayout.LayoutBounds="0.5, 0.7, 0.8, 1"
                                AbsoluteLayout.LayoutFlags="XProportional, YProportional, WidthProportional"
                                BackgroundColor="{StaticResource NL_OrangeBeer}" />-->
                        </AbsoluteLayout>
                        <AbsoluteLayout HeightRequest="{Binding EntryHeight}" WidthRequest="{Binding EntryWidth}">
                            <control:CustomEntry
                                AbsoluteLayout.LayoutBounds="0.5, 0.5, 1, 1"
                                AbsoluteLayout.LayoutFlags="All"
                                BackgroundColor="Transparent"
                                FontFamily="{extension:FontFamily Roboto_Light}"
                                FontSize="{extention:FontSize StaticResourceKey=EntryFontSize}}"
                                HasBorder="false"
                                IsPassword="True"
                                Placeholder="password"
                                PlaceholderColor="Gray"
                                Text="{Binding PasswordOne}"
                                TextColor="White"
                                XAlign="Center" />
                            <!--<BoxView
                                AbsoluteLayout.LayoutBounds="0.5, 0.7, 0.8, 1"
                                AbsoluteLayout.LayoutFlags="XProportional, YProportional, WidthProportional"
                                BackgroundColor="{StaticResource NL_OrangeBeer}" />-->
                        </AbsoluteLayout>
                        <AbsoluteLayout HeightRequest="{Binding EntryHeight}" WidthRequest="{Binding EntryWidth}">
                            <control:CustomEntry
                                AbsoluteLayout.LayoutBounds="0.5, 0.5, 1, 1"
                                AbsoluteLayout.LayoutFlags="All"
                                BackgroundColor="Transparent"
                                FontFamily="{extension:FontFamily Roboto_Light}"
                                FontSize="{extention:FontSize StaticResourceKey=EntryFontSize}}"
                                HasBorder="false"
                                IsPassword="True"
                                Placeholder="password (retype)"
                                PlaceholderColor="Gray"
                                Text="{Binding PasswordTwo}"
                                TextColor="White"
                                XAlign="Center" />
                            <!--<BoxView
                                AbsoluteLayout.LayoutBounds="0.5, 0.7, 0.8, 1"
                                AbsoluteLayout.LayoutFlags="XProportional, YProportional, WidthProportional"
                                BackgroundColor="{StaticResource NL_OrangeBeer}" />-->
                        </AbsoluteLayout>
                    </StackLayout>
                </ScrollView>
                <AbsoluteLayout
                    AbsoluteLayout.LayoutBounds="0.5,1,1,0.1"
                    AbsoluteLayout.LayoutFlags="All"
                    BackgroundColor="{StaticResource NL_OrangeBeer}">
                    <control:CustomLabel
                        AbsoluteLayout.LayoutBounds="0.5, 0.5, 1, 1"
                        AbsoluteLayout.LayoutFlags="All"
                        FontFamily="{extension:FontFamily Roboto_Light}"
                        FontSize="35"
                        HorizontalTextAlignment="Center"
                        Text="Save and Return"
                        TextColor="White"
                        VerticalTextAlignment="Center" />
                    <control:CustomButton
                        AbsoluteLayout.LayoutBounds="0.5, 0.5, 1, 1"
                        AbsoluteLayout.LayoutFlags="All"
                        BackgroundColor="Transparent"
                        BorderColor="Transparent"
                        Clicked="OnSaveClicked" />
                </AbsoluteLayout>
                <AbsoluteLayout
                    AbsoluteLayout.LayoutBounds="0, 0, 0.1, 0.1"
                    AbsoluteLayout.LayoutFlags="All"
                    BackgroundColor="Transparent"
                    IsVisible="{Binding IsReturnVisible}">
                    <control:CustomImage
                        AbsoluteLayout.LayoutBounds="0.5, 0.5, 0.8, 0.8"
                        AbsoluteLayout.LayoutFlags="All"
                        Aspect="AspectFit"
                        Source="{extension:ImageSource cross.png}" />
                    <control:CustomButton
                        AbsoluteLayout.LayoutBounds="0.5, 0.5, 1, 1"
                        AbsoluteLayout.LayoutFlags="All"
                        BackgroundColor="Transparent"
                        BorderColor="Transparent"
                        Clicked="OnReturnClicked" />
                </AbsoluteLayout>
            </AbsoluteLayout>
        </AbsoluteLayout>
    </ContentPage.Content>
</ContentPage>

куда extension:FontSize исходит от:

[ContentProperty("FontSize")]
public class FontSizeExtension : IMarkupExtension
{
    public double FontSize { get; set; }

    public object ProvideValue(IServiceProvider serviceProvider)
    {
        return Services.Sizing.FontSizeAdapter(FontSize);
    }
}

Sizing.cs

public class Sizing
{
    public static double FontSizeAdapter(double fontSize)
    {
        switch (Device.RuntimePlatform)
        {
            case "Android":
                return (fontSize / 2);
            case "iOS":
                return fontSize;
            case "Windows":
            case "WinPhone":
                return fontSize;
            default:
                return fontSize;
        }
    }
}

Тем не менее, когда я делаю FontSize="{extention:FontSize {x:StaticResource EntryFontSize}}" он выдает исключение, которое говорит, что значение не может быть нулевым. Как я могу использовать оба одновременно? Я имею в виду x:StaticResource и расширение

Благодарю

1 ответ

Решение

Изменить - 08/18

1. Убедитесь, что префикс правильно определен и используется

Убедитесь, что пространство имен, предоставленное для префикса, является правильным для вашего расширения разметки, и что при указании префикса не существует орфографической ошибки. Это должно устранить ошибку "Значение не может быть пустым".

2. Укажите имя свойства при использовании вложенных расширений разметки

Свойство-имя расширения необходимо указывать при использовании вложенной разметки-расширения. В противном случае, как показывают мои тесты, оно рассматривается как строковое значение и присваивается свойству содержимого по умолчанию. Это должно устранить ошибку "Входная строка была не в правильном формате".


Решение-1: Укажите имя-свойства

<control:CustomEntry
       AbsoluteLayout.LayoutBounds="0.5, 0.5, 1, 1"
       AbsoluteLayout.Flags="All"
   ...
       FontSize="{extension:FontSize FontSize={x:StaticResource EntryFontSize}}"
   .../>

Решение-2: Вы можете еще больше упростить это, добавив StaticResourceKey свойство в расширении разметки:

[ContentProperty("FontSize")]
public class FontSizeExtension : IMarkupExtension
{
    public double FontSize { get; set; }
    public string StaticResourceKey { get; set; }

    public object ProvideValue(IServiceProvider serviceProvider)
    {
        if (serviceProvider == null)
            throw new ArgumentNullException(nameof(serviceProvider));

        if (StaticResourceKey != null)
        {
            var staticResourceExtension = new StaticResourceExtension { Key = StaticResourceKey };
            FontSize = (double)staticResourceExtension.ProvideValue(serviceProvider);
        }

        return Services.Sizing.FontSizeAdapter(FontSize);
    }
}

и использование может быть:

   ...
       FontSize="{extension:FontSize StaticResourceKey=EntryFontSize}}"
   ...
Другие вопросы по тегам