miechooy
miechooy

Reputation: 3422

Bind ListView with Objects

I am trying to bind ListView with TestRow class as below

  <Grid Background="White">
        <ListView ItemsSource="{Binding BindingTest}" HorizontalAlignment="Left" Height="176" Margin="49,41,0,0" VerticalAlignment="Top" Width="197">
            <ListView.View>
                <GridView>
                    <GridViewColumn/>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>


  public ObservableCollection<TestRow> BindingTest
         => ListToObservableCollection<TestRow>.ObservableCollectionFromList(new List<TestRow>
         {
                new TestRow(1, "jack"),
                new TestRow(2, "mark")
         });

After start ListView shows "XXXX.TestoRow" twice. However when I am binding List<int> it is working corret. How then I can bind my own objects to ListView?

Upvotes: 1

Views: 101

Answers (1)

Vladimir
Vladimir

Reputation: 1390

Use DisplayMemberPath. If TestRow has fields:

class TestRow
{
  public int Index {get;set;}
  public string Name {get;set;}
}

then use

    <ListView ItemsSource="{Binding BindingTest}" DisplayMemberPath="Name" HorizontalAlignment="Left" Height="176" Margin="49,41,0,0" VerticalAlignment="Top" Width="197">

and selected values would be TestRow.

Upvotes: 3

Related Questions