Xamarin持续颜色选择器

nfg76nw0  于 2022-12-07  发布在  其他
关注(0)|答案(3)|浏览(165)

我做了一个按钮和颜色选择器到xamarin。表单应用程序,但我想让它当我选择一种颜色(如红色)和关闭应用程序,当我重新打开它看到这个红色自动挑选。我尝试使用这个代码,但首选项不工作的颜色:

public Color ColorPicker
{
    get => Preferences.Get(nameof(ColorPicker), color.Red);
    set
    {
        Preferences.Set(nameof(ColorPicker), value);
        OnPropertyChanged(nameof(ColorPicker));
    }
}

有人能帮帮我吗?

mtb9vblg

mtb9vblg1#

可以将Xamarin.forms.color存储为字符串,如下所示:

public string ColorPicker
{
    get => Preferences.Get(nameof(ColorPicker), Color.Red.ToString());
    set
    {
        Preferences.Set(nameof(ColorPicker), value);
        OnPropertyChanged(nameof(ColorPicker));
    }
}

然后,您可以将其绑定到Label,例如:

<Label TextColor="{Binding ColorPicker}" />

请确保在视图中设置了BindingContext。您可以阅读有关Binding here.的更多信息

2q5ifsrm

2q5ifsrm2#

Color.FromHex(string value)方法需要string类型参数。请尝试在自定义类中将value转换为字符串类型。
检查代码:
自定义转换器类

public class StringToColorConverter : IValueConverter, INotifyPropertyChanged
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var color = Color.FromHex(value as string);
        return color;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Page.xaml

<ContentPage.Resources>
    <local:StringToColorConverter x:Key="myConverter" />
</ContentPage.Resources>

<ContentPage.Content>
    <StackLayout BackgroundColor="{Binding Color_string, Converter={StaticResource myConverter}}">
        ...
    </StackLayout>
</ContentPage.Content>
5sxhfpxr

5sxhfpxr3#

我是不可能这样做的。因为我需要使用转换器后,使字符串=〉颜色。我正在尝试这样做:

public class StringToColor : IValueConverter
{
    ColorTypeConverter converter = new ColorTypeConverter();
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        //return value.ToString(); //not working
        //return (Color)(converter.ConvertFromInvariantString(value.ToString())); //not working
        return Color.FromHex(value.ToString()); //not working too
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value;
    }
}

并将此转换器添加到xaml

<ContentPage.Resources>
    <ResourceDictionary>
        <local:StringToColor x:Key="str" />
    </ResourceDictionary>
</ContentPage.Resources>

    <Label Text="TEST" FontSize="Title" TextColor="{Binding ColorPicker,
    Converter={StaticResource str}}"/>

但什么都没发生。

相关问题