WPF:ListBox中的图像路径,显示图像代替路径

时间:2011-02-24 07:48:14

标签: wpf xaml data-binding c#-4.0

我有一个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>

3 个答案:

答案 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 ItemTemplateItemsControlListBoxItem已被忽略ListBox } ListViewItem等。因此,在这种情况下,您必须直接使用ListView的ContentTemplate。

另外,将ItemContainerStyle更改为Source="{Binding Content}"

Source="{Binding}"