【问题标题】:How can I change image.source with C# when creating a UWP app?创建 UWP 应用时如何使用 C# 更改 image.source?
【发布时间】:2016-05-13 17:28:07
【问题描述】:

我正在开发我的第一个 Windows 10 UWP 应用。我有一个图像。这是它的 XAML 代码:

<Image x:Name="image" 
               HorizontalAlignment="Left"
               Height="50" 
               Margin="280,0,0,25" 
               VerticalAlignment="Bottom" 
               Width="50" 
               Source="Assets/Five.png"/>

我正在尝试使用此代码更改 image.source:

        private void slider_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)
    {
        BitmapImage One = new BitmapImage(new Uri(@"Assets/One.png"));
        BitmapImage Two = new BitmapImage(new Uri(@"Assets/Two.png"));
        BitmapImage Three = new BitmapImage(new Uri(@"Assets/Three.png"));
        BitmapImage Four = new BitmapImage(new Uri(@"Assets/Four.png"));
        BitmapImage Five = new BitmapImage(new Uri(@"Assets/Five.png"));

        if (slider.Value == 1)
        {
            image.Source = One;
        }
        else if (slider.Value == 2)
        {
            image.Source = Two;
        }
        else if (slider.Value == 3)
        {
            image.Source = Three;
        }
        else if (slider.Value == 4)
        {
            image.Source = Four;
        }
        else if (slider.Value == 5)
        {
            image.Source = Five;
        }
    }

但是当我编译代码时,我得到这个指向变量声明的错误:

UriFormatException 未被用户代码处理

【问题讨论】:

    标签: c# xaml win-universal-app


    【解决方案1】:

    Windows 运行时 API 不支持 UriKind.Relative 类型的 URI,因此您通常使用推断 UriKind 的签名并确保您指定了有效的绝对值包含方案和权限的 URI。

    要访问存储在应用程序包中的文件,但要从没有推断根权限的代码中访问,请指定 ms-appx: 方案,如下所示:

    BitmapImage One = new BitmapImage(new Uri("ms-appx:///Assets/One.png"));
    

    更多信息,请查看How to load file resources (XAML)URI schemes

    【讨论】:

      【解决方案2】:

      您需要为每个 URI 对象指定额外的 UriKind 参数,以便将它们定义为相对,例如

      new Uri("Assets/One.png", UriKind.Relative)
      

      【讨论】:

      • 您好,感谢您的帮助。然而,这导致 ArgumentsException 未被用户代码处理。有任何想法吗?谢谢
      • 看看这个类似的问题:link
      • 嗨,真的没多大用处。还是谢谢。
      猜你喜欢
      • 1970-01-01
      • 2016-04-09
      • 2018-03-14
      • 2018-06-27
      • 2018-07-02
      • 2016-08-19
      • 2015-11-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多