【问题标题】:why do it show a black screen when i use Uri class?为什么我使用 Uri 类时会显示黑屏?
【发布时间】:2015-11-14 19:07:16
【问题描述】:

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

图像服务类

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

【问题讨论】:

  • ImageService 类与 XAML 有什么关系?
  • 图片控件绑定到ImageService中的Image属性
  • 您使用的 XAML 不会这样做。
  • datacontext 已经设置为 ImageService,然后我将图像控件绑定到 Image 属性。你能解释一下我还能做些什么来解决黑屏问题吗?
  • 这是有道理的。您应该提到数据上下文设置为ImageService。我会尝试重现问题。

标签: c# visual-studio xaml windows-store-apps


【解决方案1】:

使用这个:

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

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:

      你的意思是这样吗?因为它仍然使画面变黑。

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

      【讨论】:

        猜你喜欢
        • 2010-12-31
        • 1970-01-01
        • 2019-07-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多