Reputation: 55
I have a C# code and must it write at xaml.
My code:
foreach (item i in List.Items)
{
Label lb =new Label;
lb.VerticalAlignment=Center;
lb.Content= List.Items.Name;
lb.Width="120";
mGrid.Children.Add(lb);
}
mGrid is a Grid in my xaml code. List is a List. the list became the content from a file. if in this file are 2 entry's, i had to create to labels. if there are 4, i must create 4. if there are 7, create 7. and so on.
It works fine with C#, but I have to write it in xaml code. How can I do this?
greetings
Upvotes: 1
Views: 5125
Reputation: 8162
Consider using the MVVM Pattern.
That way you have ViewModel class, that holds your list of Items in an ObservableCollection.
Your list just Binds the ItemsSource to the Collection in the ViewModel, you do no longer require to create the items in the code behind or elsewhere.
The width and VerticalAlignment go directly to the XAML as they are view specific. Even the Label will be in the View, if you need it, probably as a ItemsTemplate.
MVVM is explained in this excellent video tutorial by Jason Dollinger which is abailable on Lab49
It already includes a list and you can see there what to do.
The source code developed in this video is also available
on Lab49
Upvotes: 1