简体   繁体   English

如何在ListView中添加不同的项目

[英]How to add different items in a ListView

I have a ListView of this type: 我有一个这种类型的ListView

<ListView x:Name="LView">
    <ListView.View>
        <GridView x:Name="GView"></GridView>
    </ListView.View>
</ListView>

Initially I don't know how many columns there will be in my GridView , and I don't know what is the type of a single cell. 最初我不知道我的GridView会有多少列,我不知道单个单元格的类型是什么。

I need to have the possibility to add at run-time new columns and especially new rows whose cells contain different objects. 我需要有可能在运行时添加新列,尤其是其单元格包含不同对象的新行。

ListView has the property Items , so if I have a single column of string and Iwant to add a row i write: ListView具有属性Items ,所以如果我有一列字符串并且我想添加一行我写:

LView.Items.Add("my string");

Now i want to add a new column: 现在我要添加一个新列:

GView.Columns.Add(new GridViewColumn());

A new column is added but the second cell of the first row contains the string "my string", why? 添加了一个新列,但第一行的第二个单元格包含字符串“my string”,为什么? I don't want this behavior but a new empty cell. 我不希望这种行为,而是一个新的空单元格。

And especially if I want to add a new row with the first cell as String and the second cell as CheckBox what I have to do? 特别是如果我想添加一个新行,第一个单元格为String ,第二个单元格为CheckBox ,我必须做什么?

I tried: 我试过了:

LView.Items.Add("my second string", new CheckBox());

But, obviously, it does not work. 但是,显然,它不起作用。

I tried to add a new Object: 我试图添加一个新的对象:

public class obj
{
    public string MyString{ get; set; }
    public CheckBox MyCBox { get; set; }
}

LView.Items.Add(new obj());

But it dows not work because it display a string that contains (Namespace "+ obj"), and I don't know how many columns there will be, so I can't know how the obj class have to be initially . 但它不起作用,因为它显示一个包含(Namespace“+ obj”)的字符串, 我不知道会有多少列,所以我不知道obj类最初应该如何

What I have to do to solve my problems? 我必须做些什么来解决我的问题? Thanks. 谢谢。

I think you mix data items with ui elements 我认为你将数据项与ui元素混合在一起

LView.Items.Add("my string");

will be presented as a textelement using default template 将使用默认模板显示为textelement

If you havent defined any data templates and want to explicitly add ui elements try this instead: 如果您还没有定义任何数据模板并希望显式添加ui元素,请尝试以下方法:

LView.Items.Add(new TextBlock { Text = "My string"});

However, I think GridView is suppoused to be populated with data (along with power of data bindings), not explicitly ui elements. 但是,我认为GridView被填充了数据(以及数据绑定的强大功能),而不是显式的ui元素。 Column Template should define how data is presented (in your case an checkbox or textelement). 列模板应定义数据的呈现方式(在您的情况下为复选框或textelement)。

See example http://www.c-sharpcorner.com/uploadfile/mahesh/gridview-in-wpf/ 参见示例http://www.c-sharpcorner.com/uploadfile/mahesh/gridview-in-wpf/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM