C Sharp/Xamarin pattern for refreshing data attached to a click handler

WesleyTurnerWesleyTurner USMember
edited December 2015 in Xamarin.Android

So I'm using this pattern to remove click handlers on a button after being clicked.

dataObj = new Object(); // give this object properties

if (!button.HasOnClickListeners) {
    EventHandler GetDetails = null;
    GetDetails = delegate(object sender, EventArgs args) {
        ActivityOptions options = ActivityOptions.MakeScaleUpAnimation (button, 0, 0, 60, 60);
        Intent intent = new Intent (this, typeof(Detail));

        //get freshest object
        var toJson = Newtonsoft.Json.JsonConvert.SerializeObject (dataObj);
        intent.PutExtra ("nearestTrain", toJson);

        StartActivity (intent, options.ToBundle ());

        button.Click -= GetDetails;
    };
    button.Click += GetDetails;
}

But what I want is a way to unregister the click handler if it has already been registered.

This works well for ensuring the click handler gets removed after being used, but if I update the data, and click the button, the initial view is stale since it could not be removed after the data was updated. I have several of these buttons, so it's hard to store these handlers somewhere. How can I refresh the handler so that the data is freshest. Basically the method that updates the data also updates the event handlers, so data is updated there. If I do not de-register the handler (at the end of the anonymous event handler), then the click handler is compounded with all registrations incurred from background data updates.

I'm new to both C# and Xamarin, but I would love to hear if there is a better way so as to avoid the stale data from being viewed in the first place. Additionally when I attempt to access properties that have been set from within the main activity, I usually end up with a null pointer references. I'm sure I'm missing something basic.

Sign In or Register to comment.