Xamarin图像源AppThemeBinding到对象属性

2eafrhcq  于 2023-04-03  发布在  其他
关注(0)|答案(1)|浏览(312)

我在Xamarin项目中有一个自定义控件,它有一个ImageSource类型的binableProperty
在主视图中,我有一个集合视图,我想在ItemTemplate中绑定我的属性。
我的问题是我不能绑定我的对象属性到AppThemeBinding。
source="{Binding DarkImage}”这没有问题源="{Binding LightImage}”这没有问题
source="{AppThemeBinding Dark=DarkImage,Light=LightImage}”不起作用
source="{AppThemeBinding Dark={Binding DarkImage},Light={Binding LightImage}}”不起作用

dxpyg8gm

dxpyg8gm1#

根据这个关于AppThemeBinding an ImageButton's Source using Binding is not working的案例,你不能为xaml中的图像设置AppThemeBinding。
但是你可以在后面的代码中做到这一点。例如:

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";
                }
            };
        }

并在xaml中声明图像控件,如<Image x:Name="image" HeightRequest="300"/>

更新1:

行代码也可以在后面的代码中工作:image.SetOnAppTheme<FileImageSource>(Image.SourceProperty, "light.png", "dark.png");

更新2:

我可以在xaml中设置绑定,如:

<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>

相关问题