Khalid Hex
Khalid Hex

Reputation: 119

Binding switch value to list element by index

I have a multiple switch's (days of week) that I want to bind it to a list specific index's .. like Saturday => mylist[0] , Sunday mylist[1] right now when i try to get the value it's return null !

My ViewModel

  private List<bool> _days;

  public List<bool> Days
    {
        get => _days;
        set
        {
            if (Equals(value, _days)) return;
            _days = value;
            OnPropertyChanged();
        }
    }

My view

<Switch IsToggled="{Binding Days[0]}" Grid.Row="4" Grid.Column="0"
                Scale="1.5" x:Name="SaturdaySwitch"></Switch>
 <Switch IsToggled="{Binding Days[1]}" Grid.Row="5" Grid.Column="0"
                Scale="1.5" x:Name="SundaySwitch"></Switch>

Upvotes: 0

Views: 547

Answers (1)

Gerald Versluis
Gerald Versluis

Reputation: 34128

To show you how in code, I created this quick-and-dirty sample for you which can be found here: https://github.com/jfversluis/FixedArraySample

In the ViewModel (here named PageModel), I define a List which is initialized with 7 values.

public List<bool> Days { get; set; } = new List<bool>
{
    false,
    false,
    true,
    false,
    false,
    false,
    true
};

Then in the page, I bind it like this:

<StackLayout Orientation="Horizontal">
    <Label Text="Monday" />
    <Switch IsToggled="{Binding Days[0]}" />
</StackLayout>

This results in the screen below. Databound Switch controls

To set the values back in the list when you toggle the switches as well, you probably want to add two-way data-binding, like: <Switch IsToggled="{Binding Days[0], Mode=TwoWay}" />.

Now the values will be updated in the Days list accordingly and you can access them in your ViewModel.

Upvotes: 1

Related Questions