3

I have a WPF Image Control in my project that loads from internet (lazy loading), i want to show a initial image in Image Control until main image load. plz help me

<DataTemplate DataType="{x:Type local:MyData}">
...
 <Image Width="50" Height="50" Source="{Binding Path=profile_image_url_https, FallbackValue=profile_image_url_https}"  HorizontalAlignment="Left">
...
</DataTemplate>
H.B.
  • 166,899
  • 29
  • 327
  • 400
ArMaN
  • 2,306
  • 4
  • 33
  • 55
  • 1
    [PriorityBinding.](http://msdn.microsoft.com/en-us/library/system.windows.data.prioritybinding.aspx) –  Aug 07 '11 at 17:01

1 Answers1

4

You might be able to make it work using TargetNullValue on the binding, only set the image property when it is loaded.

e.g.

<BitmapImage x:Key="DefaultImage" UriSource="Images/Error.ico" />
<Image Source="{Binding TestBitmapImage,
                        TargetNullValue={StaticResource DefaultImage}}" />
private BitmapImage _TestBitmapImage = null;
public BitmapImage TestBitmapImage
{
    get { return _TestBitmapImage; }
    set
    {
        if (_TestBitmapImage != value)
        {
            _TestBitmapImage = value;
            PropertyChanged.Notify(() => this.TestBitmapImage);
        }
    }
}
private void Button_Click(object sender, RoutedEventArgs e)
{
    var img = new BitmapImage();
    img.DownloadCompleted += (s, dcea) =>
        {
            TestBitmapImage = img;
        };
    img.BeginInit();
    img.UriSource = new Uri("http://www.gravatar.com/avatar/c35af79e54306caedad37141f13de30c?s=128&d=identicon&r=PG");
    img.EndInit();
}
H.B.
  • 166,899
  • 29
  • 327
  • 400
  • Added something which hopefully illustrates it. (The class implement INotifyPropertyChanged so the binding updates when the property is set in the completed event.) This is just one way to do it, there are probably others... – H.B. Aug 07 '11 at 15:35
  • @ArMaN: Added that as well. It is important that the field for the property is null at first, otherwise the `TargetNullValue` won't be used. (`Notify` is an extension method which uses some reflection to raise member-name-safe change notifications) – H.B. Aug 07 '11 at 15:47
  • Error 1 The name 'PropertyChanged' does not exist in the current context – ArMaN Aug 07 '11 at 16:13
  • You cannot just copy the code, you do not even have the extension method, **this is just an illustration**. (The event comes from the interface [`INotifyPropertyChanged`](http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx), which is implemented to allow databinding to the property, **you should already know as much**) – H.B. Aug 07 '11 at 16:39