[英]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: 我想将我的列表框绑定到一个对象,而没有将wpf窗口绑定到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. 这不起作用,我的_logFiles中肯定有对象,但是lstb_logFiles不显示任何项目。 What am I doing wrong? 我究竟做错了什么?
For ListBox
to populate its item, you should set ItemsSource
and not DataContext
. 为了使ListBox
填充其项目,应设置ItemsSource
而不是DataContext
。
It should be: 它应该是:
lstb_logFiles.ItemsSource = _logFiles;
and not 并不是
lstb_logFiles.DataContext = _logFiles;
you have to set the itemssource to "self" 您必须将itemssource设置为“ self”
<ListBox ItemsSource="{Binding}"/>
or instead of setting the datacontext you can set the itemssource directly 或代替设置数据上下文,您可以直接设置itemssource
public ObservableCollection<FileLog> _logFiles = new ObservableCollection<FileLog>();
lstb_logFiles.ItemsSource= _logFiles;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.