WPF/XAML提供了许多常用数据类型的类型转换器,如Brush、Color、FontWeight、Point等,它们都是派生自TypeConverter的类(如BrushConverter、ColorConverter等)。它们都能提供自动的类型转换工作,但并不完备,如BitmapImage.UriSource绑定不工作,这时我们必须创建自己的类型转换器。
           对于BitmapImage.UriSource的转换我们可以定义以下转换器UriToImageConverter,并以资源的形式创建和引用。
< local:UriToImageConverter x:Key ="LocalUriToImageConverter"/>
当然在XAML文件中,你需要声明新的XML命名空间(通常是在XAML的根元素,如窗口或页面):
xmlns:local="clr-namespace: MyApplicationNamespace "
xmlns:地方=“CLR的命名空间:MyApplicationNamespace”
 
然后,在DataTemplate中(这是有可能在那里你会使用这个),您需要使用转换器
< Image x:Name ="imgPhoto" Width ="80" Height ="60" Grid. Row ="0"
Source ="{Binding Path=FilenameUri,
Converter={StaticResource LocalUriToImageConverter}}"
>
 
最后,添加下面的C#代码到您的项目
 
    public class UriToImageConverter : IValueConverter
    {
 
        public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
        {
            if (value == null)
            {
                return null;
            }
 
            if (value is string)
            {
                value = new Uri((string)value);
            }
 
            if (value is Uri)
            {                
                BitmapImage bi = new BitmapImage();
                bi.BeginInit();
                bi.DecodePixelWidth = 80;
                //bi.DecodePixelHeight = 60;                
                bi.UriSource = (Uri)value;
                bi.EndInit();
                return bi;
            }
 
            return null;
        }
 
        public object ConvertBack(object value, Type targetType, object parameter, 
System.Globalization.CultureInfo culture)
        {
            throw new Exception();
        }
 
    }

0

收藏

yirandexin

2篇文章,1615人气,0粉丝

Ctrl+Enter 发布

发布

取消