Alan2
Alan2

Reputation: 24572

How can I code a class to receive a property for use with custom renderers?

I have seen this coding style:

    public CustomTextCell()
    {
    }

    public static readonly BindableProperty IsCheckedProperty =
    BindableProperty.Create(
            "IsChecked", typeof(bool), typeof(CustomTextCell),
        defaultValue: false);

    public bool IsChecked
    {
        get { return (bool)GetValue(IsCheckedProperty); }
        set { SetValue(IsCheckedProperty, value); }
    }
}

and this:

public class ExtViewCell : ViewCell
{
    public bool NoTap { get; set; }
}

Can someone help explain the difference. Is one serving a different function from the other? In my case all I need is to pass to a custom renderer the value of NoTap. Should I code it like in the first or second example?

Upvotes: 0

Views: 48

Answers (1)

Paul Kertscher
Paul Kertscher

Reputation: 9723

The second one is a POCO - a plain old C# object - that is relatively self-explanatory, but serves not much more purpose that holding data - and not that much in this case.

The first one is a bit more interesting, especially in the context of MVVM. SetValue does more than just setting the value, but will (in most cases) raise PropertyChanged event (see INotifyPropertyChanged), to notify subscribers that, well, a property has changed.

Now how does this relate to your custom renderer? You could implement the property in your view as a plain property - i.e. without notifications - and it might work (cannot tell, though, since I do not know your custom renderer) when setting IsChecked initially (and without binding). Anyway, imagine you'll update the value of IsChecked. You do so from your code and wonder, why this change is not reflected in your custom renderer. But how is your renderer supposed to know? Polling each and every property might be possible for smaller forms, but is a terrible waste of resources. (And Xamarin.Forms just does not work this way.) You'll page/view has to tell your custom renderer, that something has changed. INotifyPropertyChanged to the rescue. In your custom renderer you can subscribe to PropertyChanged event and react to IsChecked being changed, updating your native view.

Upvotes: 1

Related Questions