在wpf动态创建标签 [英] create dynamically label at wpf

查看:337
本文介绍了在wpf动态创建标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C#代码,并且必须在xaml上编写.

I have a C# code and must it write at xaml.

我的代码:

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是我的xaml代码中的一个Grid.列表是一个列表.列表成为文件中的内容. 如果在此文件中是2项的,我不得不创建标签. 如果有4,我必须创建4. 如果有7,则创建7. 等等.

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.

它在C#中可以正常工作,但是我必须用xaml代码编写它.我该怎么办?

It works fine with C#, but I have to write it in xaml code. How can I do this?

问候

推荐答案

考虑使用MVVM模式.

Consider using the MVVM Pattern.

这样,您就可以拥有ViewModel类,该类可以保存项目列表 在ObservableCollection中.

That way you have ViewModel class, that holds your list of Items in an ObservableCollection.

您的列表只是将ItemsSource绑定到 ViewModel,您不再需要在后面的代码中创建项目 或其他地方.

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.

width和VerticalAlignment照原样直接转到XAML 查看特定.如果需要,即使标签也会出现在视图中, 可能作为ItemsTemplate.

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在Jason Dollinger的精彩视频教程中进行了解释 在Lab49上可用

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.

此视频中开发的源代码也可用
在Lab49上

The source code developed in this video is also available
on Lab49

这篇关于在wpf动态创建标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆