TwoWay binding works only as OneWay in custom control

EdgarasAusvicasEdgarasAusvicas DKUniversity ✭✭
edited March 2018 in Xamarin.Forms

I'm not sure if I'm misunderstanding how bindings work, but I got this problem:
I have a custom control that extends ViewCell, which has this bindable property:

private void TapGestureOnTapped(object sender, EventArgs eventArgs)
        {
            if (IsEnabled)
            {
                FavoriteChecked = !FavoriteChecked;
            }
        }
        public static readonly BindableProperty FavoriteCheckedProperty
            = BindableProperty.Create(
                nameof(FavoriteChecked),
                typeof(bool),
                typeof(StudyCell),
                defaultValue: default(bool),
                defaultBindingMode: BindingMode.TwoWay,
                propertyChanging: (bindable, oldValue, newValue) =>
                {
                    var ctrl = (StudyCell)bindable;
                    ctrl.FavoriteChecked = (bool)newValue;
                });

        public bool FavoriteChecked
        {
            get
            {
                return (bool)GetValue(FavoriteCheckedProperty);
            }
            set
            {
                SetValue(FavoriteCheckedProperty, value);
                UpdateCheckBox(value);
            }
        } 

In my page xaml I bind it simply by

<ListView>
    <ListView.ItemTemplate>
                <DataTemplate>
            <core:StudyCell FavoriteChecked="{Binding Favorite, Mode=TwoWay}" />
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

And it works as OneWay binding - it correctly reads binded variable and represents it accordingly, however, when clicked it doesn't change the source. TapGestureOnTapped above gets called, which updates the property and visually changes the control correctly, however I don't get breakpoints hit inside OnPropertyChanged of my viewmodel where source variable is.

Tagged:

Answers

  • It should work if you use OnPropertyChange() in "set"

    public bool FavoriteChecked
    {
    get
    {
    return (bool)GetValue(FavoriteCheckedProperty);
    }
    set
    {
    SetValue(FavoriteCheckedProperty, value);
    onPropertyChanged(value);
    }
    }

  • PhenmanPhenman USMember ✭✭✭
    edited October 2018

    del

Sign In or Register to comment.