Is there a way to “associate” one Xamarin Forms control with another?

Issue

I have a form with three “pairs” of {Entry, Button} defined in Xaml. Each button is intended to act on its corresponding Entry. Is there a way in the Xaml to “associate” each Entry with its Button? I am trying to avoid having to have three virtually identical methods

OnButtonAClicked()
{
    act on Entry A
}
OnButtonBClicked()
{
   act on Entry B
}
OnButtonCClicked()
{
    act on Entry C
}

I want instead one method

OnButtonClicked()
{
    act on my associated Entry
}

Is there a good way to do this?

Thanks.

Solution

use bindings (haven’t tested this, think it will work)

<Entry x:Name"EntryA" ... .>

<Button BindingContext"{x:Reference NameEntryA}" Clicked"OnButtonClicked" ... />

<Entry x:Name"EntryB" ... .>

<Button BindingContext"{x:Reference NameEntryB}" Clicked"OnButtonClicked" ... />

then

OnButtonCClicked(object sendrer, EventArgs args)
{
    Button btn  (Button)sender;

    Entry entry  (Entry)btn.BindingContext;

    // entry should be a reference to the appropriate entry
}

Answered By – Jason

Leave a Comment