[英]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.