简体   繁体   中英

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?

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;

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;

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