Nick
Nick

Reputation: 10499

How to add different items in a ListView

I have a ListView of this type:

<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.

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:

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? 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?

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.

What I have to do to solve my problems? Thanks.

Upvotes: 1

Views: 291

Answers (1)

Sebastian &#208;ymel
Sebastian &#208;ymel

Reputation: 717

I think you mix data items with ui elements

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

will be presented as a textelement using default template

If you havent defined any data templates and want to explicitly add ui elements try this instead:

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. Column Template should define how data is presented (in your case an checkbox or textelement).

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

Upvotes: 3

Related Questions