How to attach extra data to listbox items in VB.Net

萝らか妹 提交于 2020-01-06 14:56:56

问题


i'm new to visual studio and working on a project in visual basic. I am additing data to listbox from database that i need to access later.. Can we add extra data to listbox items as we can do with following html ??

<option name="harry" age="10" value="1">My name is harry</option>

any ideas please ???

regards


回答1:


You don't "attach" any data (whatever that means) to any UI elements in WPF, simply because UI is not Data.

If you're working with WPF, you really need to understand The WPF Mentality, which is very different from other approaches used in other technologies.

In WPF, you use DataBinding to "Bind" the UI to the Data, as opposed to "putting" or "storing" the data in the UI.

This is an example of how you Bind a ListBox to a collection of data items in WPF:

XAML:

<ListBox ItemsSource="{Binding MyCollection}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding FirstName}"/>
                <TextBlock Text="{Binding LastName}"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

ViewModel:

public class MyViewModel
{
    public ObservableCollection<MyData> MyCollection {get;set;}

    //methods to create and populate the collection.
}

Data Item:

public class MyData
{
    public string LastName {get;set;}

    public string FirstName {get;set;}
}

I strongly suggest that you read up on MVVM before starting to code in WPF. Otherwise you'll hit walls quickly and waste too much time in unneeded code.



来源:https://stackoverflow.com/questions/19097831/how-to-attach-extra-data-to-listbox-items-in-vb-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!