这应该非常简单,但我无法让它工作...
CustomItem 是一个具有名为 ThumbnailImage 的属性的类 我正在尝试将 ObservableCollection 绑定(bind)到 ListBox 以显示图像。这是我的代码:
public ObservableCollection<CustomItem> AvailableItems { get; set; }
<ListBox Width="103" Height="480" ItemsSource="{Binding AvailableItems}">
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Black" BorderThickness="1">
<ContentControl Content="{Binding Path=ThumbnailImage}"
Width="100" Height="100" />
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
CustomItem 看起来像这样
public class CustomItem
public Image ThumbnailImage { get; set; }
}
当我运行它时,列表框中没有显示任何内容。知道出了什么问题吗?谢谢!
-- 编辑 1 -- 我想我可以从调试中得知当 AvailableItems.Count == 5 时 closet.Items.Count == 0。我尝试添加 ItemsSource="{Binding AvailableItems, UpdateSourceTrigger=PropertyChanged}"但这没有帮助:(
-- 编辑 2 --
我在我的 XAML 中做了以下事情
DataContext="{Binding RelativeSource={RelativeSource Self}}"
相反,当我在代码隐藏中执行以下操作时,一切正常:
DataContext = this;
最佳答案
您发布的代码似乎没问题,所以问题一定出在其他地方
ListBox
是否具有正确的 DataContext,以便它可以正确绑定(bind)到AvailableItems
?- 您如何在代码中初始化您的
Image
?
例子
BitmapImage source = new BitmapImage();
source.BeginInit();
source.UriSource = new Uri(yourUriString, UriKind.RelativeOrAbsolute);
source.EndInit();
ThumbnailImage = new Image();
ThumbnailImage.Source = source;
我将您的代码粘贴到一个示例项目中并且运行良好,已将其上传到此处
http://www.mediafire.com/download.php?m99kv1uglrr31j9
将它与您的版本进行比较,看看您缺少什么
关于WPF - 将列表框绑定(bind)到图像的 ObservableCollection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5266382/