Dennis van Opstal
Dennis van Opstal

Reputation: 1338

Xamarin Forms: Binding 2 properties to another one

I have a HorizontalListView (from SharpNado) and I have some buttons to navigate between the different items. I want these buttons only to be visible under certain conditions(they can both be visible at the same time):

If the current index of the listview is greater than 0, the "previous" button should be visible. If the current index of the listview is lower than the highest index (count - 1) I want the "next" button to be visible.

I want to use some binding between views (with converters) to solve this. I have managed to bind the "previous" button's visibility to the current index with a converter that checks if the index is greater than 0, but I'm struggling a lot with the "next" button since it needs to change when either the current index or the amount of items in te list changes.

I've tried a lot of stuff with converterparameters, but I can't bind through them. I've also tried an option where the converter had a binding, but that wouldn't even build.

This is the HorizontalListView I'm using, and at this point it's too late too switch to an alternative, since I'm too far in to this.

At this point I'm really not certain what to do and I'm hoping someone here can help me. Thanks in Advance.

EDIT:

Example Control

This is the control I'm trying to build.

Upvotes: 0

Views: 116

Answers (1)

fmaccaroni
fmaccaroni

Reputation: 3916

In your ViewModel add a getter property:

public bool IsLowerThanTheHighestIndex => this.MyIndex < this.MyList.Count - 1;

Then bind the button visibility to that property.

Then raise your changes where you need to:

private int _myIndex;
public int MyIndex
{
    get
    {
        return this._myIndex;
    }
    set
    {
        this._myIndex = value;
        OnPropertyChanged(nameof(MyIndex));
        OnPropertyChanged(nameof(IsLowerThanTheHighestIndex));
    }
}

and everywhere you modify MyList also raise the change, e.g.:

this.MyList.Add(...);
OnPropertyChanged(nameof(IsLowerThanTheHighestIndex));

If you are using an ObservableCollection<T> you can subscribe to the CollectionChanged event and call OnPropertyChanged(nameof(IsLowerThanTheHighestIndex)); in the event callback (remember to unsubscribe the event at the end)

HIH

Upvotes: 1

Related Questions