Xamarin持久性色彩选择器

问题描述 投票:0回答:2

https:/ibb.co547mg3r - 有我做的图片

你好啊

我为xamarin.forms应用制作了一个按钮和颜色选择器,但我想让它在我选择一种颜色(如红色)并关闭应用时,当我重新打开它时,看到红色自动被选中。我试着使用这段代码,但偏好设置不能与颜色一起工作。

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

谁能帮帮我?

c# xamarin xamarin.forms get set
2个回答
0
投票

Color.FromHex(string value) 方法需要一个 string 类型参数。尝试将 价值 变成自定义类中的字符串类型。

检查代码。

自定义转换器类

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();
    }
}

页面.xaml

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


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

1
投票

你可以将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 这里。


0
投票

我不可能把它做成这样。因为我需要使用转换器后,使字符串=>颜色。我正在尝试这样做。

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

但什么都没有发生...

© www.soinside.com 2019 - 2024. All rights reserved.