xamarinxamarin.formsimagesource

Xamarin Image Source AppThemeBinding to object properties


I have a custom control in my Xamarin project. It has a binableProperty of type ImageSource

In main view i have a collection view where i want to bind my properties inside ItemTemplate.

My problem is that i cant bind my object properties to AppThemeBinding.

source="{Binding DarkImage}" this does work without problems source="{Binding LightImage}" this does work without problems

source="{AppThemeBinding Dark=DarkImage, Light=LightImage}" does NOT work

source="{AppThemeBinding Dark={Binding DarkImage}, Light={Binding LightImage}}" does NOT work


Solution

  • According to this case about AppThemeBinding an ImageButton's Source using Binding is not working, you can't set a AppThemeBinding for the image in the xaml.

    But you can do this in the code behind. Such as:

    public MainPage()
            {
                InitializeComponent();
                if (Application.Current.RequestedTheme == OSAppTheme.Light)
                {
                    image.Source = "test.jpg";
                }
               else
                {
                    image.Source = "test2.png";
                }
                Application.Current.RequestedThemeChanged += (s, e) =>
                {
                    if(e.RequestedTheme == OSAppTheme.Light)
                    {
                        image.Source = "test.jpg";
                    }
                    else
                    {
                        image.Source = "test2.png";
                    }
                };
            }
    

    And declare the image control in the xaml such as <Image x:Name="image" HeightRequest="300"/>

    Update1:

    The line code also work in the code behind : image.SetOnAppTheme<FileImageSource>(Image.SourceProperty, "light.png", "dark.png");

    Update2:

    I can set the binding in the xaml such as:

    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 x:Class="App23.MainPage">
        <ContentPage.Resources>
            <Style x:Key="MyImage" TargetType="Image" >
                <Setter Property="Source"
                    Value= "{AppThemeBinding Light=light.jpg,Dark=dark.png}"
                />
            </Style>
        </ContentPage.Resources>
        <StackLayout>
            <Image x:Name="image" HeightRequest="300" Style="{StaticResource MyImage}"/>
        </StackLayout>