create dynamically label at wpf

江枫思渺然 提交于 2020-01-05 07:09:31

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/11590571/create-dynamically-label-at-wpf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!