简体   繁体   中英

DataBinding to ListView

I have a class

public class Foo
    {
        public List<string> list1 { get; set;}
        public List<string> list2 { get; set; }  
        public string url;
    }

and a ListView with two columns

 <ListView Name="listview" ItemsSource="{Binding}">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="list1" 
                       DisplayMemberBinding="{Binding Path=list1}" />
                <GridViewColumn Header="list2" 
                       DisplayMemberBinding="{Binding Path=list2}" />
            </GridView>
        </ListView.View>
    </ListView>

How i can to bind instance of Foo class to ListView?

Here i set a DataContext

listview.DataContext = new Foo()
                                       {
                                           list1 = new[] { "dsfasd", "asdfasdf", "asdf", "asdfsd" }.ToList(),
                                           list2 = new[] { "dsfasd", "asdfasdf", "asdf", "asdfasd" }.ToList()
                                       };

But it's not work.

我将在代码后面将其datacontext设置为Foo实例。

Not sure what you are trying to do, but list1 and 2 are two collections. ItemsSource itself must be a collection (or possibly at least an Ienumerable, I don't know off my head). I don't see that your class Foo implements anything that resemblles a collection. You will not be able to bing to list1/2 that way.

You can eg let Foo implement IEnumerable<KeyValuePair<string,string>> and then yield out Key Value pairs with your strings. Then you could bind to Properties Key and Value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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