简体   繁体   中英

why do it show a black screen when i use Uri class?

I'm creating a simple windows store app in c#. When i'm binding my image control to display an image from code- behind, my screen goes black. Anyone know how i can solve the problem?

ImageService Class

public class ImageService 
{     

  public Image Image { get; set; }      

    public ImageService()
    {
        var uri = new System.Uri("ms-appx:///assets/Logo.scale-100.png");
        var bmp = new BitmapImage(uri);
        Image.Source = bmp;
    }
}

XAML file

  <Image x:Name="image" HorizontalAlignment="Left" Height="223"     Margin="394,279,0,0" VerticalAlignment="Top" Width="305" Source="{Binding Image, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Stretch="UniformToFill"/>

Use this:

public class ImageService
{
    public Uri Image { get; set; }
    public ImageService()
    {
        Image = new Uri("ms-appx:///assets/Logo.scale-100.png");
    }
}

The Source property of an Image is of type ImageSource which can be easily replaced by a Uri . (MSDN) .

Images in XAML have a built in converter so you can just bind to a Uri, you don't have to create an Image in the service.

Your service isn't implementing INotifyPropertyChanged so if you set your image in your service outside the constructor your view won't update.

I don't see in your code where you are instantiating your Image. Image will be null so when your view loads, the Image will be null resulting in a blank image on your view.

You mean like this? Cause it still makes the sceen go black.

public class ImageService : INotifyPropertyChanged
{
    private Uri _uri;

    public Uri Uri
    {
        get { return _uri; }
        set
        {
            _uri = value;
            OnPropertyChanged();
        }
    }

    public ImageService()
    {
        Uri = new Uri("ms-appx///assets/Logo.scale-100.png");                                                
    }

    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM