ʞᴉɯ
ʞᴉɯ

Reputation: 5594

Xamarin Style staticresource binding

would it be possible to databind a static resource in Xamarin Forms? Something like

Style="{StaticResource {Binding foo, StringFormat='SomeStyle{0}'}}"

Thanks

Upvotes: 1

Views: 3437

Answers (1)

Joe
Joe

Reputation: 420

What you probably want is a Value Converter that handles locating the StaticResource for you. Full Microsoft Documentation here.

On your XAML element, you'd do something like this:

<Entry Style="{Binding foo, Converter={StaticResource FooToStyleConverter}}"/>

Your converter would work something like this:

public class FooToStyleConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var someValue = (string)value; // Convert 'object' to whatever type you are expecting

        // evaluate the converted value
        if (someValue != null && someValue == "bar")
            return (Style)App.Current.Resources["StyleOne"]; // return the desired style

        return (Style)App.Current.Resources["StyleTwo"];
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // Usually unused, but inverse the above logic if needed
        throw new NotImplementedException();
    }
}

Lastly, set up your converter as a Static Resource in App.xaml (or as a local resource on the page) so your page can properly reference it

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:DataBindingDemos">
    <ContentPage.Resources>
         <ResourceDictionary>
              <local:FooToStyleConverter x:Key="FooToStyleConverter" />
              ....

Upvotes: 7

Related Questions