[英]How to bind the source of an image to a directory + name in wpf?
I have a list of image files that I want to create a datagrid based on them and show a thumbnail. 我有一个图像文件列表,我想基于它们创建数据网格并显示缩略图。 The list contains images files related to a path such as follow:
该列表包含与路径相关的图像文件,例如:
class myclass
{
public List<string> images;
public string RootPath;
}
I need to write a converter to bind to two parameter and then create a thumbnail and the result became the source of images. 我需要编写一个转换器以绑定到两个参数,然后创建一个缩略图,结果成为图像的来源。
I already wrote an converter to create the source of image as follow: 我已经写了一个转换器来创建图像源,如下所示:
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;
}
But this converter bind to only one property, but I need to generate a way to bind it to two (or more) values? 但是此转换器仅绑定到一个属性,但是我需要生成一种将其绑定到两个(或更多)值的方法? How can I do this?
我怎样才能做到这一点?
You might use a multi-value converter as shown in the following ItemsControl example. 您可以使用下面的ItemsControl示例中所示的多值转换器。 It uses a
MultiBinding
for the Source
property of the Image control, where the first binding uses the DataContext
of the ItemsControl to access the RootPath
property. 它对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>
The example assumes that the view model class looks like this: 该示例假定视图模型类如下所示:
public class ViewModel
{
public List<string> Images { get; set; }
public string RootPath { get; set; }
}
The converter could be implemented like this: 转换器可以这样实现:
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.