Sam
Sam

Reputation: 4339

Global markup extensions in Xamarin Forms

Is it possible to create a global reference for a markup extension in Xamarin Forms?

I'm using a markup extension to provide localization, and would like to register the namespace once, rather than in every view.

For example, here is a simple page:

<?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="Views.Home"
             xmlns:i18n="clr-namespace:App.Globalization">
    <ContentPage.Content>
        <StackLayout HorizontalOptions="Fill" VerticalOptions="Center">
            <Label Text="{i18n:Translate Welcome}"
                   HorizontalOptions="Center"/>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

What I want to do is not require every page to include the xmlns:i18n namespace, but include it globally.

Upvotes: 0

Views: 330

Answers (2)

Sharada
Sharada

Reputation: 13601

Short answer: No. It's not possible, unless you switch your xmlns definitions. And also please note this is a XML limitation, not just XAML.

How this works:

The only way to do this is through use of XmlnsDefinitionAttribute. XAML parsers (both compile-time, and run-time) look for these attributes on assemblies to glean the default global namespace declarations much like following line in AssemblyInfo in Xamarin.Forms.Core.

[assembly: XmlnsDefinition("http://xamarin.com/schemas/2014/forms", "Xamarin.Forms")]

You can find some of these parsing methods here.

The above line coupled with this attribute

xmlns="http://xamarin.com/schemas/2014/forms"

that is included by default in your custom XAML pages/views, allow you to directly use controls like ContentPage, StackLayout, Grid etc. without having to specify the Xamarin.Forms namespace

Now, you can see both XmlnsDefinitionAttribute, and XmlTypeExtensions are marked as internal. So there is no easy way to get around it.

What you can try is switching your xmlns namespace definitions as following (please note I am sharing this just for illustration purpose only). This will allow you to not have to specify prefix for TranslateExtension.

<f:ContentPage xmlns="clr-namespace:App.Globalization" 
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
             xmlns:local="clr-namespace:SampleApp"
             xmlns:f="http://xamarin.com/schemas/2014/forms"
             x:Class="SampleApp.MainPage">
    <f:ContentPage.Content>
        <f:StackLayout HorizontalOptions="Fill" VerticalOptions="Center">
            <f:Label Text="{Translate Welcome}"
                   HorizontalOptions="Center"/>
        </f:StackLayout>
    </f:ContentPage.Content>
</f:ContentPage>

Upvotes: 0

Immons
Immons

Reputation: 257

No. The same applies for C# code - can you declare using of some namespace globally? Of course not.

Upvotes: -1

Related Questions