[英]How to bind the source of an image to a directory + name in wpf?
我有一个图像文件列表,我想基于它们创建数据网格并显示缩略图。 该列表包含与路径相关的图像文件,例如:
class myclass
{
public List<string> images;
public string RootPath;
}
我需要编写一个转换器以绑定到两个参数,然后创建一个缩略图,结果成为图像的来源。
我已经写了一个转换器来创建图像源,如下所示:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
try
{
var bi = new BitmapImage();
bi.BeginInit();
bi.DecodePixelWidth = 100;
bi.CacheOption = BitmapCacheOption.OnLoad;
bi.UriSource = new Uri(value.ToString());
bi.EndInit();
return bi;
}
catch
{
// do nothing. Maybe return a default image
}
return null;
}
但是此转换器仅绑定到一个属性,但是我需要生成一种将其绑定到两个(或更多)值的方法? 我怎样才能做到这一点?
您可以使用下面的ItemsControl示例中所示的多值转换器。 它对Image控件的Source
属性使用MultiBinding
,其中第一个绑定使用ItemsControl的DataContext
访问RootPath
属性。
<ItemsControl x:Name="itemsControl" ItemsSource="{Binding Images}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Image Stretch="None">
<Image.Source>
<MultiBinding Converter="{StaticResource ImagePathConverter}">
<Binding Path="DataContext.RootPath"
ElementName="itemsControl"/>
<Binding/>
</MultiBinding>
</Image.Source>
</Image>
</DataTemplate>
</ItemsControl.ItemTemplate>
该示例假定视图模型类如下所示:
public class ViewModel
{
public List<string> Images { get; set; }
public string RootPath { get; set; }
}
转换器可以这样实现:
public class ImagePathConverter : IMultiValueConverter
{
public object Convert(
object[] values, Type targetType, object parameter, CultureInfo culture)
{
var path = Path.Combine(values.OfType<string>().ToArray());
var bi = new BitmapImage();
bi.BeginInit();
bi.DecodePixelWidth = 100;
bi.CacheOption = BitmapCacheOption.OnLoad;
bi.UriSource = new Uri(path);
bi.EndInit();
return bi;
}
public object[] ConvertBack(
object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.