nix
nix

Reputation: 2285

How to change ViewCell items values?

I have a code like this:

class CustomCell : ViewCell
{
    private readonly Label _label;

    public static readonly BindableProperty DataProperty = BindableProperty.Create("Data", typeof(string), typeof(CustomCell), "Data");

    public string Data
    {
        get { return (string)GetValue(DataProperty); }
        set { SetValue(DataProperty, value); }
    }

    ...

    protected override void OnBindingContextChanged()
    {
        base.OnBindingContextChanged();

        if (BindingContext != null)
        {
                _label.Text = Data;
        }
    }
}

It works just fine, when I use this code to pass value to it in ListView:

<customUi:CustomCell Data="{Binding Data}" />

However, sometimes I want to be able to change Data from CustomCell itself. When I change it simply by writing this.Data = "new value"; the label text doesn't change. I could write simply _label.Text = "new value";, it works, but it just feels wrong. Also, changing Data and then calling OnBindingContextChanged() feels wrong as well.

What is the correct way of doing it?

Upvotes: 1

Views: 872

Answers (2)

irreal
irreal

Reputation: 2296

Just like you have created a bindable property called "Data" on your class. The property "Text" of the Label control is also bindable. So you can apply the same binding to it, and it should work as expected. The common pattern is to have the binding context of your control contain the necessary properties, to which you would then bind the properties of individual controls. So instead of binding to a Data property and then re-applying that property to the label, just edit the CustomCell itself and give the label's text property this same binding

<Label Text="{Binding Data}" />

You can even take specific objects from your viewmodel and pass them as binding context for the cell, so that the controls inside the cell always have the same structure to bind to

<customUi:CustomCell BindingContext="{Binding SomeItem}" />
//Assuming SomeItem is a property inside your VM, or binding context of wherever the CustomCell is

Now bind the label's text property and any other properties of any other controls inside the CustomCell to properties of SomeItem.


In case you really want to create a bindable property on the viewcell and then just pass it through to the label, you can also take whatever binding is applied to the "Data" property of the CustomCell on it's property changed event and apply the same binding to the Text property of the label. Though this should not be needed really.

Upvotes: 2

eakgul
eakgul

Reputation: 3698

Override OnPropertyChanged method like:

    protected override void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        base.OnPropertyChanged(propertyName);
        if (propertyName == "Data")
            _label.Text = Data;
    }

Upvotes: 0

Related Questions