我有一个ListBox填充了不同图像的路径。我将如何更改ItemTemplate,以便显示图像而不是路径(字符串)。
以下是代码:
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate>
<Image Height="50" Width="50" Source="{Binding Path=Content}" Stretch="Fill"></Image>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBoxItem>C:\Users\AKSHAY\Pictures\IMG0083A.jpg</ListBoxItem>
<ListBoxItem>C:\Users\AKSHAY\Pictures\IMG0102A.jpg</ListBoxItem>
<ListBoxItem>C:\Users\AKSHAY\Pictures\IMG0103A.jpg</ListBoxItem>
<ListBoxItem>C:\Users\AKSHAY\Pictures\IMG0104A.jpg</ListBoxItem>
<ListBoxItem>C:\Users\AKSHAY\Pictures\IMG0105A.jpg</ListBoxItem>
<ListBoxItem>C:\Users\AKSHAY\Pictures\IMG0106A.jpg</ListBoxItem>
</ListBox>
答案 0 :(得分:2)
您可以创建一个将字符串转换为ImageSource的IValueConverter。
类似的东西:
public class ImagePathConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return new BitmapImage(new Uri(value as string));
}
public object ConvertBack(xxx) { throw new NotSupportedException(); }
}
然后创建一个值转换器资源并在绑定中使用它。
资源可以定义为:
<UserControl.Resources>
<myNameSpaceAlias:ImagePathConverter x:Key="ImagePathConverter"/>
...
然后绑定:
{Binding Path=Content, Converter={StaticResource ImagePathConverter}}
答案 1 :(得分:0)
您必须在绑定中使用值转换器并传递位图图像
答案 2 :(得分:0)
在UI生成期间,ItemTemplate
的{{1}}被复制到ListBox
的{{1}}。但是,直接添加ContentTemplate
时,ListBoxItem
的容器类型(ListBoxItem
ItemTemplate
已ItemsControl
,ListBoxItem
已被忽略ListBox
} ListViewItem
等。因此,在这种情况下,您必须直接使用ListView
的ContentTemplate。
另外,将ItemContainerStyle
更改为Source="{Binding Content}"
Source="{Binding}"