为什么我使用 Uri class 时显示黑屏?

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

我正在用 C# 创建一个简单的 windows 商店应用程序。当我绑定我的图像控件以显示来自代码隐藏的图像时,我的屏幕变黑了。有人知道我该如何解决这个问题吗?

图像服务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 文件

  <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"/>

XAML 中的图像具有内置转换器,因此您只需绑定到 Uri,而不必在服务中创建图像。

您的服务未实现 INotifyPropertyChanged,因此如果您在构造函数之外的服务中设置图像,您的视图将不会更新。

我在你的代码中没有看到你在哪里实例化你的图像。图像将为空,因此当您的视图加载时,图像将为空,从而导致您的视图上出现空白图像。

你是说这样?因为它仍然使屏幕变黑。

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

使用这个:

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

图像的 Source 属性 是 ImageSource 类型,可以很容易地用 Uri 替换。 (MSDN).