Bill Software Engineer
Bill Software Engineer

Reputation: 7792

Binding listbox to object without window datacontext

I would like to bind my listbox to an object without the wpf window binding to a datacontext:

<ListBox Height="Auto" HorizontalAlignment="Left" Margin="0,0,0,0" Name="lstb_logFiles" VerticalAlignment="Stretch" Width="100" SelectionChanged="lstb_threadList_SelectionChanged">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding dateName,StringFormat=\{0\}}" Foreground="Orange" Margin="10,3,0,3" Width="80" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

And here is where I setup the binding

public ObservableCollection<FileLog> _logFiles = new ObservableCollection<FileLog>();
lstb_logFiles.DataContext = _logFiles;

This doesn't work, my _logFiles definitely have object in it, but lstb_logFiles does not show any items. What am I doing wrong?

Upvotes: 0

Views: 97

Answers (2)

Rohit Vats
Rohit Vats

Reputation: 81253

For ListBox to populate its item, you should set ItemsSource and not DataContext.

It should be:

lstb_logFiles.ItemsSource = _logFiles;

and not

lstb_logFiles.DataContext = _logFiles;

Upvotes: 1

blindmeis
blindmeis

Reputation: 22445

you have to set the itemssource to "self"

  <ListBox ItemsSource="{Binding}"/>

or instead of setting the datacontext you can set the itemssource directly

  public ObservableCollection<FileLog> _logFiles = new ObservableCollection<FileLog>();
  lstb_logFiles.ItemsSource= _logFiles;

Upvotes: 0

Related Questions