Home > Net >  Assign x:Name property to a checkbox in source code [Xamarin/C#]
Assign x:Name property to a checkbox in source code [Xamarin/C#]

Time:05-05

Hello I have set of check boxes that are generated from source code and not in XAML. Now, I wanted to set x:Name during creation of it so that I can loop through each element using the FindByName. I planned on setting name like checkbox1, checkbox2, checkbox3...

So that I can use this FindByName

        foreach (var  qaItem in question.Entity.QuestionAnswer)
        {
            (FindByName($"checkbox{qaItem.OrderNum}") as CheckBox).IsChecked = false;
        }

Is there a way to set "x:Name" in source? since the number of checkboxes is not definite.

CodePudding user response:

x:Name is not actually a property, it is just a XAML helper that is used to create a C# variable name. If you are creating the elements at runtime, you need to maintain an array or list in order to keep track of them

you could do something like this

Dictionary<string,Checkbox> myCheckboxList = new Dictionary<string,Checkbox>();

then as you create each checbox

var cb = new Checkbox();
... set properties, etc ...
myCheckboxList.Add(qaItem.OrderNum, cb);
  • Related