0

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

1 Answers1

0

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>
Liyun Zhang - MSFT
  • 8,271
  • 1
  • 2
  • 14
  • In Codebehind you can set it like: image.SetOnAppTheme(Image.SourceProperty, item.ImageSourceLightMode, item.ImageSourceDarkMode); I think it is better way But you say it is not possbile in XAML ? – Stefan Vogel Mar 28 '23 at 08:52
  • Sorry for my careless, you can check the update part in my answer. And the ansewr in the link I provided has explained why the way you used themebinding didn't work. @StefanVogel – Liyun Zhang - MSFT Mar 28 '23 at 09:20
  • Tank you a lot :) i know all the solutions but i hoped it is possible with bindings in xaml :/ But thank you very very much i got my answer from you :) – Stefan Vogel Mar 28 '23 at 11:08