我有一个图像文件的列表,我想要创建一个数据的基础上,并显示一个缩略图。该列表包含与路径相关的图像文件,如下所示:
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;
}但是这个转换器只绑定到一个属性,但是我需要生成一种将其绑定到两个(或更多)值的方法?我该怎么做?
发布于 2014-03-24 21:36:02
您可以使用多值转换器,如下面的ItemsControl示例所示。它使用MultiBinding作为图像控件的Source属性,其中第一个绑定使用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();
}
}https://stackoverflow.com/questions/22615966
复制相似问题