简体   繁体   中英

How can I assign an id for radiobutton and access it at code behind in Xamarin Forms in order to not check both radiobuttons

xaml code

<input:RadioButton  x:Name="button1" Clicked="Radio_Button_Clicked" 
       Grid.Column="1" Value="btn1" 
       Style="{StaticResource radiofontsize}">
</input:RadioButton>

<input:RadioButton x:Name="button2" Clicked="Radio_Button_Clicked"  
       Grid.Column="2" Value="btn2" 
       Style="{StaticResource radiofontsize}">
</input:RadioButton>

C#

private void Radio_Button_Clicked(object sender, EventArgs e)
{
}

You have already assigned the StyleId to your buttons which is the x:Name setting in the XAML.

Try the below code. It will help you.

private void Radio_Button_Clicked(object sender, EventArgs e)
{
    var styleId = (sender as RadioButton).StyleId;
    if(styleId == "button1")
    {
        //Do your logic here for the button1 selection.
    }
    else
    {
        //Do your logic here for the button2 selection.
    }
}

Like @Harikrishnan said, you could also use ClassId .

 <Button ClassId="btn1" x:Name="button1" />
        <Button ClassId="btn2" x:Name="button2"  Clicked="button2_Clicked"/>

 private void button2_Clicked(object sender, EventArgs e)
    {
        var btn = sender as Button;
        var id = btn.ClassId;

        //.....
    }

Or you could use FindByName to get the name id of button control.

 var s = this.FindByName<Button>("button1");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM