WPF MultiBinding IMultiValueConverter

WPF 绑定多个属性和多个转换器

示例:图标绑定本地和远程图片

XAML代码:

<ResourceDictionary xmlns:cvt="clr-namespace:Micro.Converter;assembly=Micro.Common">
<cvt:BitmapImageMultiConverter x:Key="BitmapImageMultiConverter"/>

 

<Image MaxWidth="180" VerticalAlignment="Top" HorizontalAlignment="Center" Stretch="Fill">
    <Image.Source>
        <MultiBinding Converter="{StaticResource BitmapImageMultiConverter}">
            <Binding Path="local_uri"/>
            <Binding Path="image_uri"/>
        </MultiBinding>
    </Image.Source>
</Image>

 C# 转换器代码

public class BitmapImageMultiConverter : IMultiValueConverter
{
    /// <summary>
    /// 加载本地或者网络图片
    /// 调用示例:
    /// <Image.Source>
    /// <MultiBinding Converter="{StaticResource BitmapImageMultiConverter}">
    /// <Binding Path="local_uri"/>
    /// <Binding Path="image_uri"/>
    /// </MultiBinding>
    /// </Image.Source>
    /// </summary>
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (values == null || values.Length < 1)
        {
            return null;
        }

        String localUri = System.Convert.ToString(values[0]);
        if (!String.IsNullOrEmpty(localUri))
        {
            return ImageHelper.LocalBitmapImage(localUri);
        }

        String imageUri = System.Convert.ToString(values[1]);
        if (!String.IsNullOrEmpty(imageUri))
        {
            return ImageHelper.RemoteBitmapImage(localUri);
        }

        return null;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

 

posted @ 2021-07-04 01:26  microsoft-zhcn  阅读(149)  评论(0编辑  收藏  举报