简体   繁体   English

当我使用Uri类时,为什么显示黑屏?

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

I'm creating a simple windows store app in c#. 我正在用c#创建一个简单的Windows应用商店。 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 ImageService类别

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

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 . Image的Source属性的类型为ImageSource ,可以轻松地由Uri替换。 (MSDN) . (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. XAML中的图像具有内置的转换器,因此您可以绑定到Uri,而不必在服务中创建图像。

Your service isn't implementing INotifyPropertyChanged so if you set your image in your service outside the constructor your view won't update. 您的服务未实现INotifyPropertyChanged,因此,如果您在构造函数之外的服务中设置图片,则视图不会更新。

I don't see in your code where you are instantiating your Image. 我在您的代码中看不到要实例化Image的位置。 Image will be null so when your view loads, the Image will be null resulting in a blank image on your view. Image将为null,因此在加载视图时,Image将为null,从而导致视图上出现空白图像。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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