bocko
bocko

Reputation: 398

Xamarin.Forms XAML binding to x:String

Is there a way to dynamicaly assign Picker.Items from XAML?

Something like:

<Picker x:Name="pckTheme">
    <Picker.Items>
        <x:String>{Binding Option1Text}></x:String>
        <x:String>{DynamicResource Option2Text}></x:String>
    </Picker.Items>
</Picker>

(This sample is not working, of course).

As far as I can tell, the only allowed type in Picker.Items is x:String and I can't seem to find any method to bind to x:String.

Doing it from code is relatively simple, but I would prefer doing it from XAML directly, if possible.

Goal here is to localize content from resource file, but other uses may come handy.

Upvotes: 4

Views: 1890

Answers (3)

benk
benk

Reputation: 446

<x:string> only supports constant values. You can address this issue with a Markup Extension

Its functionality is trivial: it returns its parameter.

using System;
using Xamarin.Forms.Xaml;

namespace YOURAPP.Extensions
{
    public class StringExtension : IMarkupExtension
    {
        public string Value { get; set; }

        public object ProvideValue(IServiceProvider serviceProvider)
        {
            return Value;
        }
    }
}

Use it like this in a view:

  1. Add xmlns:ext="clr-namespace:YOURAPP.Extensions" to the root element
  2. <ext:StringExtension Value="{anything here}" /> where you would otherwise want <x:string>

Note that this causes an Add to be called to the IEnumerable. For the picker it works out of the box. For custom controls it requires initialization (to avoid a NullReferenceException) and and ObservableCollection to make sure that the view is updated on adding.

Upvotes: 0

DigitApps
DigitApps

Reputation: 91

Please use the following XAML code:

<x:Array Type="{x:Type x:String}">
<x:Static Member="local:AppResources.Events"/>
<x:Static Member="local:AppResources.Device"/>
<x:Static Member="local:AppResources.Biographical"/>
</x:Array>

Where local is:

xmlns:local="clr-namespace:YOURNAMESPACE"

Upvotes: 2

Steven Thewissen
Steven Thewissen

Reputation: 2981

Normally you would bind the Picker to a list of items which can be as dynamic as you want. To put them in there as hardcoded items isn't really dynamically assigning if you ask me. What you could do is create a ValueConverter to use in your XAML that gets the language specific value of a key and bind the Picker to a list of keys.

Upvotes: 1

Related Questions