Search code examples
xamarinxamarin.formsxamarin.android

Bind value for "Maximum' property not working on Slider Xamarin


I am trying to use a ViewModel property on Slider Maximum value, but when I use Binding the slider always show the current value as 0.

With fixed values, it works:

<Slider Minimum="0" Maximum="16" Value="{Binding SliderStep, Mode=OneWay}" HorizontalOptions="CenterAndExpand" />

enter image description here

But the Maximum value is variable, so I need to Bind it from ViewModel, when I try do it something goes wrong:

<Slider Minimum="0" Maximum="{Binding SliderMax}" Value="{Binding SliderStep, Mode=OneWay}"  HorizontalOptions="CenterAndExpand" />

enter image description here

ViewModel Piece Code:

double sliderStep;
    public double SliderStep
    {
        get
        {
            return sliderStep;
        }
        set { sliderStep = value;
            OnPropertyChanged("SliderStep");
        }
    }

    double sliderMax;
    public double SliderMax
    {
        get
        {
            return sliderMax;
        }
        set {
            sliderMax = value;
            OnPropertyChanged();
        }
    } 
public SectionGraphicViewModel(INavigation navigation)
        {
            this.Navigation = navigation;
            sectionRep = new SectionRepository();
            this.Sections = sectionRep.GetSections().ToList();
            Items = new List<SectionGraphicModel>();
            foreach (var item in this.Sections)
            {
                var SectionView = new SectionModel(item);
                Items.Add(new SectionGraphicModel(){ Source = SectionView.CachedImageUsed.Source, Desc = SectionView.Desc, Id = SectionView.Id });
            }
            SliderMax = items.Count();
            if (sectionId.HasValue)
            {
                SliderStep = items.FindIndex(x => x.Id == sectionId);
            }
            else
            {
                SliderStep = 0;
            }
        }

The Maximum value on this example is 16, I tested with different values and the result is the same. I tested only on Android simulator. I don't know if it happens on iOS.

PS: Just to avoid misunderstanding, I need to make the Maximum property Bind a value from VM, and OneWay, the control will be disabled from UI, just showing the value from VM.


Solution

  • You should set properties in an order that ensures that Maximum is always greater than Minimum, Maximum should be set before Minimum in xaml:

    <Slider  BackgroundColor="Aquamarine" Maximum="{Binding SliderMax}" Minimum="0" Value="{Binding SliderStep}" IsEnabled="False"  VerticalOptions="EndAndExpand" ></Slider>
    

    If you want to disable the UI, set:

    IsEnabled="False"
    

    Refer: slider#precautions