tags:

views:

333

answers:

1

Hello, I have ListBox and want to put values in this listbox from DataTable:

listBoxVisibleFields.DataContext = SelectedFields;

Where SelectedFields is a DataTable filled with data. But this code does not work. My listbox is empty. As i remember, in WinForms was sucha a thing for list box like ValueMember and DisplayMember, but in WPF I dont find something like that...Does someone know how to fill simply my listbox from DataTable?

A: 

The property you are looking for is ItemsSource instead of DataContext. The property most closely resembling ValueMember is called SelectedValuePath (see this example). The analogon for DisplayMember is called DisplayMemberPath.


EDIT: So, your code should look like this:

DataTable SelectedFields = ...;
listBoxVisibleFields.SelectedValuePath = "myID";
listBoxVisibleFields.DisplayMemberPath = "myTextField";
listBoxVisibleFields.ItemsSource = SelectedFields.DefaultView;

Alternatively, the two path values can be set in XAML

<ListBox ... SelectedValuePath="myID" DisplayMemberPath="myTextField" />

which is a bit more elegant.

Heinzi
Ok, i changed it to :listBoxVisibleFields.ItemsSource = SelectedFields as IEnumerable;But his does not work to, listbox is empty anyway.
Vytas
Try `SelectedFields.DefaultView`.
Heinzi
Using `as` in such situations is dangerous, since it fails silently if the cast fails rather than throwing an exception.
Heinzi
Ok, thank Yuo man, everything works perfect now :-).
Vytas
Maybe yuo also know how to set myId and myTextField for an comboBoxEdit in Devexpress WPF? I have posted earlier a question on that, but no one answered it...
Vytas
Unfortunately, I have no experience with the Devexpress stuff, but binding a "normal" WPF ComboBox works just like a ListBox.
Heinzi