I have a ListBox filled with paths of different images. How will I alter the ItemTemplate so that the images will be shown instead of paths(string).
Here is the code:
<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\AKS开发者_StackOverflow中文版HAY\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>
You could make an IValueConverter that converts a string to a ImageSource.
Something like:
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(); }
}
And then create a value converter resource and use that in your binding.
a resource could be defined like:
<UserControl.Resources>
<myNameSpaceAlias:ImagePathConverter x:Key="ImagePathConverter"/>
...
and then bind with:
{Binding Path=Content, Converter={StaticResource ImagePathConverter}}
The ItemTemplate
of a ListBox
is copied to the ContentTemplate
of a ListBoxItem
during UI generation. However, when adding the ListBoxItem
s directly, ItemTemplate
is ignored for items already of the ItemsControl
s container type (ListBoxItem
for ListBox
, ListViewItem
for ListView
etc.). So in this case, you'll have to use the ContentTemplate of the ItemContainerStyle
directly instead.
Also, change Source="{Binding Content}"
to Source="{Binding}"
<ListBox>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<Image Height="50" Width="50" Source="{Binding}" Stretch="Fill"></Image>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
<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>
You have to use a value converter in the binding and pass a bitmap image
精彩评论