将数据模板图像绑定到WPF中的自定义对象属性
我有一个集合 private ObservableCollection<ImageData> imageDataList = new ObservableCollection<ImageData>();
ImageData是一个自定义对象。它具有一个称为fileName
的属性,该属性存储图像文件的完整路径。在我的XAML代码中,我有一个带有datatemplate的列表框,如下所示。将数据模板图像绑定到WPF中的自定义对象属性
<ListBox Name="listBox_ImageList" Grid.ColumnSpan="3" Grid.Row="2" SelectionChanged="listBox_ImageList_SelectionChanged">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Image Source="{Binding fileName}" Height="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ListBox, AncestorLevel=1}, Path=ActualHeight}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
填充ImagaData
物体进入imageDataList
后,我设置this.listBox_ImageList.ItemsSource = imageDataList;
然而,当我运行它,我没有看到任何图片。你能告诉我如何恰当地将数据绑定到WPF图像源的对象的字符串成员?
设置的DataContext到其中的ObservableCollection位于
DateContext = this;
将其绑定
而且代替文件名到ImageSource的属性或一个BitmapImage的属性,这是使用创建的对象文件名。
我想你可以使用像Juan Carlos Vega Neira建议的转换器 – MyKuLLSKI 2012-01-12 16:30:56
回答您的问题:您无法将ImageSource属性绑定到字符串。它在XAML中起作用,因为当您在XAML中设置值时,WPF使用从字符串到ImageSource的默认转换器。如果您想使用绑定或代码设置值,则需要提供ImageSource对象。
有2种方式通过结合做到这一点:
第一个提出here(链接胡安·卡洛斯·提到的),它涉及到创建的IValueConverter,将您的字符串,并将其转换为一个ImageSource的。我会修改这个介绍那里的转换代码:
public sealed class StringToImageSourceConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
try
{
return new BitmapImage(new Uri((string)value));
}
catch
{
return DependencyProperty.UnsetValue;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
第二个选项是在你的ImageData类来创建你的ImageSource和直接绑定到它。
private ImageSource _imageSource
public ImageSource ImageSource
{
get
{
if (_imageSource == null)
{
_imageSource = new BitmapImage(new Uri(fileName), UriKind.RelativeOrAbsolute);
}
return _imageSource;
}
}
你看到_anything_?如果你注释掉ListBox.ItemTemplate代码(你应该看到[ImagaData.ToString()]),你看到了什么? – 2012-01-12 16:05:32