如何使用绑定为Xamarin中的滑块赋予某些颜色

问题描述

我创建了一个滑块来知道1-100之间的确切位置,现在我想根据范围更改颜色,0-50绿色(带有“ OK”),50-90黄色(带有)文字“小心”,并且超过90红色带有文字“危险”。但是我什至不能使它在90以上的红色下工作。

MainPageviewmodel.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Windows.Input;
using Xamarin.Forms;

namespace App1
{
    public class MainPageviewmodel : INotifyPropertyChanged
    {
        private double slider;
        public double Slider
        {
            get => slider;
            set
            {
                slider = value;
                OnPropertyChanged(nameof(Slider).ToString());
                OnPropertyChanged(nameof(Color).ToString());
            }
        }
   
        public string Color()
        {
            if (Slider > 90)
            {
                return "Red";
            }
            else return "Black";
        }

        public ICommand ResetCommand { get; set; }

        public MainPageviewmodel()
        {
            ResetCommand = new Command(Reset);
        }

        private void Reset()
        {
            Slider = double.MinValue;
        }
        private void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this,new PropertyChangedEventArgs(propertyName));
        }


        public event PropertyChangedEventHandler PropertyChanged;
    }
}

这是我的

MainPage.xaml

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="App1.MainPage">

    <StackLayout>
        <Frame BackgroundColor="#2196F3" Padding="24" CornerRadius="0">
            <Label HorizontalTextAlignment="Center" 
                   Text="Title"
                   TextColor="White" 
                   FontSize="36"/>
        </Frame>
        <Label HorizontalTextAlignment="Center" 
                   Text="{Binding Slider}"
                   TextColor="{Binding Color}" 
                   FontSize="36"/>
        <Slider VerticalOptions="FillAndExpand"
                Value="{Binding Slider}"
                Maximum="100" />
        <Button Text="Reset" Command="{Binding ResetCommand}"></Button>
    </StackLayout>

</ContentPage>

尝试使用属性

public Color mycolor;
public Color MyColor
{
    get => mycolor;
    set
    {
        mycolor = value;
        {
            if (Slider > 90)
            {
                OnColorChanged(Color.Red);
            }
            else OnColorChanged(Color.Yellow);
        }

    }
}

private void OnColorChanged(Color propertyName)
{
    PropertyChanged?.Invoke(this,new PropertyChangedEventArgs(propertyName.ToString()));
}

解决方法

Color必须是一个公共属性,它返回一个Color,而不是一个string

    private double slider;
    public double Slider
    {
        get => slider;
        set
        {
            slider = value;
            OnPropertyChanged(nameof(Slider).ToString());
            OnPropertyChanged(nameof(Color).ToString());
        }
    }

    public Color Color
    {
        get {
          if (Slider > 90)
          {
            return Color.Red;
          }
          else return Color.Black;
        }
    }
,

在这种情况下,请始终使用Converter。

第1步-ViewModel

private int slider = 10;
public int Slider { get => slider; set { slider = value; OnPropertyChanged("Slider"); } }

第2步-转换器

public class SliderValueToColorConverter : IValueConverter
    {
        public object Convert(object value,Type targetType,object parameter,CultureInfo culture)
        {
            // int is if you bind via property
            if (value is int sliderVal)
            {
                if (sliderVal < 50)
                    return Color.Green;
                else if (sliderVal >= 50 && sliderVal < 90)
                    return Color.Yellow;
                else
                    return Color.Red;
            }
            // double is you bind via x:reference
            else if (value is double sliderVal2)
            {
                if (sliderVal2 < 50)
                    return Color.Green;
                else if (sliderVal2 >= 50 && sliderVal2 < 90)
                    return Color.Yellow;
                else
                    return Color.Red;
            }
            return Color.Black;
        }

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

第3步-查看

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:local="clr-namespace:DummyTestApp"
             mc:Ignorable="d" x:Name="BottomTabGridPageXaml"
             x:Class="DummyTestApp.BottomTabGridPage"
             BindingContext="{x:Reference BottomTabGridPageXaml}">
    <ContentPage.Resources>
        <local:SliderValueToColorConverter x:Key="SliderValueToColorConverter"/>
    </ContentPage.Resources>
    <ContentPage.Content>
        <StackLayout Margin="5" Padding="5" Spacing="5" VerticalOptions="CenterAndExpand">
            <Label HorizontalTextAlignment="Center" FontSize="36"
                   Text="{Binding Source={x:Reference mySlider},Path=Value}"
                   TextColor="{Binding Source={x:Reference mySlider},Path=Value,Converter={StaticResource SliderValueToColorConverter}}"/>
            <Slider x:Name="mySlider" VerticalOptions="FillAndExpand" Value="{Binding Slider}" Maximum="100" 
                    MinimumTrackColor="{Binding Slider,Converter={StaticResource SliderValueToColorConverter},Mode=TwoWay}"/>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>
,

表达式TextColor="{Binding Color}"类似于“我想绑定到名为“颜色”的字段。您需要指定要绑定到的对象或类。这是代码的缺失部分:{ 3}}。在xamarin中进行设置很麻烦,但是如果您进行了真正的MVVM设计BindingContext,它应该可以工作。