首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将图像源绑定到wpf中的目录+名称?

如何将图像源绑定到wpf中的目录+名称?
EN

Stack Overflow用户
提问于 2014-03-24 17:06:15
回答 1查看 885关注 0票数 0

我有一个图像文件的列表,我想要创建一个数据的基础上,并显示一个缩略图。该列表包含与路径相关的图像文件,如下所示:

代码语言:javascript
复制
class myclass
{
    public List<string> images;
    public string RootPath;

} 

我需要写一个转换器绑定到两个参数,然后创建一个缩略图,结果成为图像的来源。

我已经编写了一个转换器来创建图像源,如下所示:

代码语言:javascript
复制
    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;
    }

但是这个转换器只绑定到一个属性,但是我需要生成一种将其绑定到两个(或更多)值的方法?我该怎么做?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-03-24 21:36:02

您可以使用多值转换器,如下面的ItemsControl示例所示。它使用MultiBinding作为图像控件的Source属性,其中第一个绑定使用ItemsControl的DataContext来访问RootPath属性。

代码语言:javascript
复制
<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>

该示例假设视图模型类如下所示:

代码语言:javascript
复制
public class ViewModel
{
    public List<string> Images { get; set; }
    public string RootPath { get; set; }
}

转换器的实现方式如下:

代码语言:javascript
复制
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();
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22615966

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档