设置图像源

Ron*_*Ron 2 c# wpf image imagesource windows-store-apps

我正在尝试将图像源设置为来自我的计算机(而不是资源).
这就是我试图这样做的方式:

Uri uri = new Uri(@"D:\Riot Games\about.png", UriKind.Absolute);
ImageSource imgSource = new BitmapImage(uri);

this.image1.Source = imgSource;
Run Code Online (Sandbox Code Playgroud)

我尝试了几乎所有我能在互联网上找到的东西,但似乎没什么用.

知道为什么吗?

XAML:

<UserControl
    x:Class="App11.VideoPreview"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App11"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="250"
    d:DesignWidth="250">

    <Grid>
        <Button Height="250" Width="250" Padding="0" BorderThickness="0">
            <StackPanel>
                <Image Name="image1" Height="250" Width="250"/>
                <Grid Margin="0,-74,0,0">
                    <Grid.Background>
                        <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0" Opacity="0.75">
                            <GradientStop Color="Black"/>
                            <GradientStop Color="#FF5B5B5B" Offset="1"/>
                        </LinearGradientBrush>
                    </Grid.Background>
                    <TextBlock x:Name="textBox1" TextWrapping="Wrap" Text="test" FlowDirection="RightToLeft" Foreground="White" Padding="5"/>
                </Grid>
            </StackPanel>
        </Button>
    </Grid>
</UserControl>
Run Code Online (Sandbox Code Playgroud)

Roh*_*ats 7

您无法直接从Windows metro应用程序访问磁盘驱动器.从Windows应用商店应用中的文件访问权限中提取

默认情况下,您可以使用Windows应用商店应用访问某些文件系统位置,例如应用安装目录,应用数据位置和"下载"文件夹.应用还可以通过文件选择器或通过声明功能访问其他位置.

但是Pictures library,通过启用包清单文件中的功能,您可以访问一些特殊文件夹,例如文档库等.因此,从清单文件启用图片库后,此代码将起作用(复制图片库文件夹中的about.png文件)

    private async void SetImageSource()
    {
        var file = await 
          Windows.Storage.KnownFolders.PicturesLibrary.GetFileAsync("about.png");
        var stream = await file.OpenReadAsync();
        var bitmapImage = new BitmapImage();
        bitmapImage.SetSource(stream);

        image1.Source = bitmapImage;
    }
Run Code Online (Sandbox Code Playgroud)

但理想的解决方案是将您的文件包含在您的应用程序中,并将其构建操作设置为Content,以便可以将其与其他内容文件一起复制到Appx文件夹中.然后你可以像这样设置图像源 -

    public MainPage()
    {
        this.InitializeComponent();
        Uri uri = new Uri(BaseUri, "about.png");
        BitmapImage imgSource = new BitmapImage(uri);
        this.image1.Source = imgSource;
    }
Run Code Online (Sandbox Code Playgroud)

或者您只能在XAML中执行此操作:

<Image x:Name="image1" Source="ms-appx:/about.png"/>
Run Code Online (Sandbox Code Playgroud)

以下是您可以从应用程序访问的特殊文件夹列表 -

  1. 本地应用数据
  2. 漫游应用数据
  3. 临时应用数据
  4. App安装位置
  5. 下载文件夹
  6. 文件库
  7. 音乐库
  8. 图片库
  9. 视频库
  10. 可卸除的设备
  11. 家庭组
  12. 媒体服务器设备

要从清单文件启用功能,请双击Package.appxmanifest解决方案中的文件并Pictures Library选中功能选项卡下的复选框,以便为您的应用程序启用它.同样,您可以为要访问的其他文件夹执行此操作.

在此输入图像描述