WPF图像绑定&转换器不工作

时间:2015-12-05 06:01:01

标签: c# wpf

  //in xaml
  //resource
  <local:LocalUriToImageConverter x:Key="MyImageConverter"/>
  //datacontext
  DataContext="{x:Static local:GlobalData.CustomServiceInfo}"
  //image **exception throw at UriSource ** 
  <Image Height="60" Width="60" >
            <Image.Resources>
                <BitmapImage UriSource="{Binding HeadPicUrl , Converter={StaticResource MyImageConverter}}" x:Key="image1"  />
                <FormatConvertedBitmap Source="{StaticResource image1}" x:Key="formattedImage" DestinationFormat="Gray32Float" />
            </Image.Resources>
            <Image.Style>
                <Style  TargetType="Image">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Status}" Value="True">
                            <Setter Property="Source" Value="{StaticResource image1}"></Setter>
                        </DataTrigger>
                        <DataTrigger Binding="{Binding Status}" Value="False">
                            <Setter Property="Source" Value="{StaticResource formattedImage}"></Setter>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Image.Style>
  </Image>

  --------------------------------------------------------------------------
  //Code
  //model
  public class CustomServiceInfo
    {
        public string Name { get; set; }
        public string HeadPicUrl { get; set; }
        public bool Status { get; set; }

    }
 //init
 public MainWindow()
        {

        GlobalData.CustomServiceInfo = new CustomServiceInfo {
            Name = "nainaigu",
            HeadPicUrl = @"http://avatar.csdn.net/0/5/5/1_haifengzhilian.jpg",
            Status = true ,
            //Type = new Uri("pack://application:,,,/" + "MahAppsDemo" + ";component/" + "Image/my.jpg", UriKind.RelativeOrAbsolute)
            //Type = "pack://application:,,,/" + "MahAppsDemo" + ";component/" + "Image/my.jpg"
        };

        InitializeComponent();
      }

   //Custom Coverter 
   public class LocalUriToImageConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string path = (string)value;
            int BytesToRead = 100;
            try
            {
                var image = new BitmapImage();
                WebRequest request = WebRequest.Create(new Uri(path, UriKind.Absolute));
                request.Timeout = -1;
                WebResponse response = request.GetResponse();
                Stream responseStream = response.GetResponseStream();
                BinaryReader reader = new BinaryReader(responseStream);
                MemoryStream memoryStream = new MemoryStream();

                byte[] bytebuffer = new byte[BytesToRead];
                int bytesRead = reader.Read(bytebuffer, 0, BytesToRead);

                while (bytesRead > 0)
                {
                    memoryStream.Write(bytebuffer, 0, bytesRead);
                    bytesRead = reader.Read(bytebuffer, 0, BytesToRead);
                }

                image.BeginInit();
                memoryStream.Seek(0, SeekOrigin.Begin);

                image.StreamSource = memoryStream;
                image.EndInit();
                return image;
            }
            catch (Exception)
            {
                return new BitmapImage();
            }

        }

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

异常消息是{"must set the “UriSource” or “StreamSource”."}enter image description here

我认为转换不是因为我在Convert方法中设置了调试点,但异常抛出之前。 我不知道上面的代码出了什么问题。 这是我在stackoverflow中的第一个问题。 请帮帮我。谢谢!

1 个答案:

答案 0 :(得分:0)

子控件在Image.Resources中定义,而不是在Image中定义。请按如下方式更新xaml代码:

<Image Width="45" Height="45" x:Name="headPicture" Cursor="Hand" Source="{Binding HeadPicUrl, Converter={StaticResource MyImageConverter}}" >               
            <Image.Style>
                <Style  TargetType="Image">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Status}" Value="True">
                            <Setter Property="Source" Value="{StaticResource image1}"></Setter>
                        </DataTrigger>
                        <DataTrigger Binding="{Binding Status}" Value="False">
                            <Setter Property="Source" Value="{StaticResource formattedImage}"></Setter>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Image.Style>
  </Image>