initial image in WPF Image Control

2019-02-19 03:45发布

问题:

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>

回答1:

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();
}