Hello, everyone!
I'm a newbie with Xamarin, and I'm having some troubles to understand the binding syntax.
The thing is that I'm writing an app and in some part of it I need to retreive a List of attributes from a Database (that's done) and show in a ListView with a Switch to set them as yes/no.
The problem is that I need to have the List separated to the bool[ ] or List(bool> because when I press a button, I need to convert that bool list onto an Hex string.
So, this is the way I did it:
I call a command in my ViewModel to retrieve the List from my database:
Command _LoadCustomerAttributesListCommand;
public Command LoadAttributesListCommand
{
get
{
return _LoadAttributesListCommand ?? (_LoadAttributesListCommand =
new Command(async () => await ExecuteLoadAttributesListCommand()));
}
}
public async Task<List<string>> ExecuteLoadAttributesListCommand()
{
return await OtherClass.GetAttributesList();
}
Then, I use this information in my xaml.cs file to create manually the elements to an empty ListView I put on the page:
attributesList = await ((MyViewModel)BindingContext).ExecuteLoadAttributesListCommand();
if ((attributesList != null) && (attributesList.Count > 0))
{
attributesListView.Children.Clear();
for (int i = 0; i < attributesList.Count; i++)
{
attributesListView.Children.Add(CreateAttributeStackLayout(attributesList[i]);
}
}
private StackLayout CreateAttributeStackLayout(string attributeName)
{
StackLayout tempStackLayout;
Label tempLabel;
Switch tempSwitch;
tempLabel = new Label()
{
Text = attributeName,
VerticalOptions = LayoutOptions.FillAndExpand
};
tempSwitch = new Switch()
{
VerticalOptions = LayoutOptions.CenterAndExpand,
IsToggled = false,
Margin = new Thickness(0, 0, 0, 0)
};
tempStackLayout = new StackLayout()
{
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children =
{
tempSwitch,
tempLabel
}
};
return tempStackLayout;
}
attributesList is a private list on my xaml.cs class. I would Like to have a bool[ ] on my ViewModel, and use LoadAttributesListCommand to set it's size to the same as the returned attributesList, that's the easy part. But then I would like to Bind the Switchs values to the bool values, and I tried to pass it as a parameter to CreateAttributeStackLayout, to bind it in the Switch creation, with no luck (I don't know how to do it).
I'm aware about using DataTemplate, but I need those lists been separated for an easy string conversion, and also, be capable to reuse the same CreateAttributeStackLayout with another attribute list on the same page. So I hope you can help me.
Also, if you know an easier way to do this, I will try to understand it. As I said, I'm pretty new with Xamarin
Thank you (for this, and for all the help I got before from this forum!)