Gruutak
Gruutak

Reputation: 83

WPF - Filling a ListView

I have a 2 column ListView and I'm trying to fill it using and IDictionary with the following code.

System.Collections.IDictionary entryList = Environment.GetEnvironmentVariables(EnvironmentVariableTarget.User);

foreach (System.Collections.DictionaryEntry de in entryList)
{
    Row row = new Row();
    row.Name1 = (string)de.Key;
    row.Name2 = (string)de.Value;
    this.list1.Items.Add(row);
}

public class Row
{
    public string Name1 { get; set; }
    public string Name2 { get; set; }
}

XAML:

<ListView x:Name="varList"
    Grid.ColumnSpan="1"
    HorizontalAlignment="Left"
    VerticalAlignment="Top"
    Height="400"
    Width="500"
    Margin="0, 30, 0, 0">

    <ListView.View>
        <GridView>
            <GridViewColumn Width="150" Header="Name" />
            <GridViewColumn Width="350" Header="Path" />
        </GridView>
    </ListView.View>
</ListView>

But every row and column gets filled with "Project.Views.Row". Anyone got any idea on how to fix it? Thank you very much.

Upvotes: 1

Views: 836

Answers (1)

BradleyDotNET
BradleyDotNET

Reputation: 61349

A ListView (and every other control for that matter) will display the results of calling ToString when given an object to display.

For a standard class, thats its qualified name; Project.Views.Row in your example.

There are two ways to fix this:

  1. Don't add an object. Instead, format the string as you want it ie:

    list1.Items.Add(String.Format({0}:{1}, row.Name1, row.Name2));
    
  2. Do this the right way and use MVVM. In this case your XAML needs a data template:

    <ListView ItemsSource="{Binding Rows}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                   <TextBlock Text="{Binding Name1}"/>
                   <TextBlock Text="{Binding Name2}"/>
                </StackPanel>
            </DataTemplate>
        <ListView.ItemTemplate>
     </ListView>
    

    For a grid view:

     <ListView.View>
        <GridView>
           <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name1}" />
           <GridViewColumn Header="Path" DisplayMemberBinding="{Binding Name2}"/>
        </GridView>
     </ListView.View>
    

Binding the ItemsSource is not actually necessary, but since we are doing everything the right way, you should do it so you are not directly manipulating the UI from code.

Upvotes: 2

Related Questions