如何根据Xamarin表单中“滑块”的值来更改使用降级颜色的背景颜色?

时间:2019-04-15 21:08:45

标签: xamarin.forms

我有一个ListView,每个元素都有一个Slider。我需要的是当Slider的值在<20和> 2之间时,能够用其他颜色更改背景颜色。 目前,我所拥有的是一个将两个2种颜色转换为渐变背景的类,如下所示。 另外,我能做的是,在加载屏幕时,将转换为降级的颜色。但是当Slider的值在<20和> 2之间时,如果我想修改值以能够更改颜色,则不会执行该操作。

//Clase para convertir en colores degradados
public class ValueToTextConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if ((double)value < 20 && (double)value > 2)
        {
            return "Editado";
        }

        return "Ejemplo";
    }

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

//Pagina principal: Archivo XAML
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
         xmlns:local="clr-namespace:PruebasXamarin" 
         xmlns:local2="clr-namespace:PruebasXamarin.CustomControls; assembly:PruebasXamarin"
         x:Class="PruebasXamarin.MainPage">
<ContentPage.Resources>
    <ResourceDictionary>
        <local:ValueToTextConverter x:Key="ValueToText"/>
    </ResourceDictionary>
</ContentPage.Resources>
<ContentPage.Content>

    <local2:GradientColorStack StartColor="{Binding PrimerColor, Mode=OneWay}" EndColor="{Binding SegundoColor, Mode=OneWay}">
    <StackLayout x:Name="colorBa">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="8*" />
                <ColumnDefinition Width="Auto" />
            </Grid.ColumnDefinitions>
            <Label x:Name="label" Grid.Row="0" Grid.Column="0" FontSize="Large"
                                        FontAttributes="Bold"
                                        HorizontalOptions="Center"
                                        TextColor="White"/>

        </Grid>

        <ListView x:Name="ListaTareas" SeparatorVisibility="None"
                      HasUnevenRows="True">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout>
                            <Grid Margin="10" ColumnSpacing="0" BackgroundColor="White" >
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="*"/>
                                </Grid.RowDefinitions>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="8"/>
                                    <ColumnDefinition Width="*"/>
                                    <ColumnDefinition Width="*"/>
                                    <ColumnDefinition Width="*"/>
                                </Grid.ColumnDefinitions>


                                <Label 
                                            Grid.Row="0"
                                            Grid.Column="1"
                                            Text="{Binding nombre}" 
                                            TextColor="Black" 
                                            FontSize="14"
                                            FontAttributes="Bold"
                                            Margin="4"
                                            BackgroundColor="White"/>

                                <Slider x:Name="mySlider"
                                        Grid.Row="0"
                                        Grid.Column="2"
                                        Minimum="0"
                                        Maximum="4"
                                        Value="{Binding valor}"
                                        ValueChanged="mySlider_ValueChanged"></Slider>
                                <Label 
                                            Grid.Row="0"
                                            Grid.Column="3"
                                            Text="{Binding Source={x:Reference mySlider},Path=Value,Converter={StaticResource ValueToText}}" 
                                            TextColor="Black" 
                                            FontSize="14"
                                            FontAttributes="Bold"
                                            Margin="4"
                                            BackgroundColor="White"
                                            HorizontalOptions="End"/>
                            </Grid>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>
    </local2:GradientColorStack>
</ContentPage.Content>

// Pagina负责人:Archivo CS

namespace PruebasXamarin
{
public partial class MainPage : ContentPage, INotifyPropertyChanged
{

    readonly List<Tarea> listaTarea = new List<Tarea>();
    public event PropertyChangedEventHandler PropertyChanged;


    private string primerColor, segundoColor;
    public string PrimerColor
    {
        get
        {
            return this.primerColor;
        }
        set
        {
            if (this.primerColor != value)
            {
                this.primerColor = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(this.PrimerColor)));
            }
        }
    }
    public string SegundoColor 
    { 
        get
        {
            return this.segundoColor;
        } 
        set
        {
            if (this.segundoColor != value)
            {
                this.segundoColor = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(this.SegundoColor)));
            }
        }
    }


    public MainPage()
    {
        InitializeComponent();
        llenarLista();
        ListaTareas.ItemsSource = listaTarea;
        BindingContext = this;
    }
    public void llenarLista()
    {

        listaTarea.Add(new Tarea
        {
            nombre = "Alex1",
            valor = "10",
            descripcion = "Ejemplo"
        });
        listaTarea.Add(new Tarea
        {
            nombre = "Alex2",
            valor = "20",
            descripcion = "Ejemplo"
        });


        this.PrimerColor = "#0CABA1";
        this.SegundoColor = "#A9AB0C";

        //primerColor = "#AB0C2E";
        //segundoColor = "#0C6AAB";
    }

    private void mySlider_ValueChanged(object sender, ValueChangedEventArgs e)
    {
        var sliders = sender as Slider;
        var item = sliders.Parent.BindingContext as Tarea;


        this.PrimerColor = "#AB0C2E";
        this.SegundoColor = "#0C6AAB";
    }
}

}

1 个答案:

答案 0 :(得分:0)

您应该在此处使用CustomRenderer

  1. 这是GradientColorStackRenderer您的示例渲染器 可以先参考。
  2. 如果您准备好本文,还可以添加 [i][j]在渲染器中

GradientColorStack.cs与文章不同:

OnElementPropertyChanged

对于Android:

public class GradientColorStack : StackLayout
{
    public GradientColorStack()
    {

    }

    public static readonly BindableProperty StartColorProperty = BindableProperty.Create("StartColor", typeof(Color), typeof(GradientColorStack), null);

    public Color StartColor
    {
        get { return (Color)GetValue(StartColorProperty); }
        set { SetValue(StartColorProperty, value); }
    }

    public static readonly BindableProperty EndColorProperty = BindableProperty.Create("EndColor", typeof(Color), typeof(GradientColorStack), null);

    public Color EndColor
    {
        get { return (Color)GetValue(EndColorProperty); }
        set { SetValue(EndColorProperty, value); }
    }
}

Then it can work now

对于IOS :有点不同。需要将listview的背景色设置为[assembly: ExportRenderer(typeof(GradientColorStack), typeof(GradientColorStackRenderer))] namespace App10.Droid { public class GradientColorStackRenderer : ViewRenderer { public GradientColorStackRenderer(Context context) : base(context) { } private Color StartColor { get; set; } private Color EndColor { get; set; } protected override void DispatchDraw(global::Android.Graphics.Canvas canvas) { #region for Vertical Gradient //var gradient = new Android.Graphics.LinearGradient(0, 0, 0, Height, #endregion #region for Horizontal Gradient var gradient = new Android.Graphics.LinearGradient(0, 0, Width, 0, #endregion this.StartColor.ToAndroid(), this.EndColor.ToAndroid(), Android.Graphics.Shader.TileMode.Mirror); var paint = new Android.Graphics.Paint() { Dither = true, }; paint.SetShader(gradient); canvas.DrawPaint(paint); base.DispatchDraw(canvas); } protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.View> e) { if (e.OldElement != null || Element == null) { return; } try { var stack = e.NewElement as GradientColorStack; this.StartColor = stack.StartColor; this.EndColor = stack.EndColor; Console.WriteLine("OnElementChanged:"); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("ERROR:", ex.Message); } base.OnElementChanged(e); } protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); Console.WriteLine("OnElementPropertyChanged:"); var stack = sender as GradientColorStack; if(e.PropertyName == nameof(stack.StartColor)) { this.StartColor = stack.StartColor; } if (e.PropertyName == nameof(stack.EndColor)) { this.EndColor = stack.EndColor; } } } }

BackgroundColor="Transparent"

这里是Sample link