【问题标题】:Item image not shown when using a CollectionViewSource in a Windows Store app在 Windows 应用商店应用程序中使用 CollectionViewSource 时未显示项目图像
【发布时间】:2012-09-26 20:12:01
【问题描述】:

我在 Visual Studio 中基于 Grid App XAML 模板创建了一个 Windows 应用商店应用。它将GridView 绑定到包含组的集合,其中每个组包含项目,其中每个项目包含一些元数据和图像。 CollectionViewSource 用于在网格视图中显示组内的项目。这一切都很好。然后我添加了一个用于添加新项目的按钮,当单击该项目时,会显示其元数据,但 不是 图像。点击事件处理程序:

private void Button_Click_1(object sender, RoutedEventArgs e)
{
    SampleDataGroup sampleDataGroup = SampleDataSource.GetGroup("Group-1");
    var sampleDataItem = new SampleDataItem("uniq", "Title", "Subtitle", "c:/users/christian/pictures/my_image.jpg", "Description", "Content", sampleDataGroup);
    sampleDataGroup.Items.Add(sampleDataItem);
}

但是,如果图像是从项目的 Assets 文件夹中读取的,而不是从 Pictures 文件夹中读取的,则它会按预期工作。有什么想法吗?

【问题讨论】:

    标签: xaml windows-8 windows-runtime


    【解决方案1】:

    您无法直接访问 Win8 应用中的文件系统,因此您的图像路径 (c:/users/christian/pictures/my_image.jpg) 将无法在 XAML 中加载图像。

    最好的办法是使用 ImageSource 对您的类进行编码,并在您的图像文件名更改时将其加载到 C# 中。

    See here for an example.

    【讨论】:

    • 谢谢,我尝试了here 给出的建议,它奏效了。我想这与您链接到的示例大致相同。
    【解决方案2】:

    正如 ZombieSheep (LOL) 所提到的,您无法像那样访问文件系统。将图像添加到(例如)项目中的 Assets 文件夹并像这样引用它:(图像称为 boot.jpg,View 中的元素称为 MyImage)。使用 collectionviewsource 时也是一样,只需设置正确的路径(ms-appx:/// 或使用 this.UriBase,或定义一个包含 uri 基本字符串的静态只读属性)。

    希望这会有所帮助:)

     public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            SetImage();
        }
    
        private static readonly Uri _baseUri = new Uri("ms-appx:///");
    
        void SetImage()
        {
            MyImage.UriSource = new Uri(this.BaseUri, "Assets/boot.jpg");
            //MyImage.Source = new BitmapImage(new Uri("ms-appx:///Assets/boot.jpg"));
            //MyImage.Source = new BitmapImage(new Uri(_baseUri,"/Assets/boot.jpg"));
        }
    }
    

    您必须设置一个新的 BitmapImage 或在视图中定义 BitmapImage 并设置 Uri :)

    【讨论】:

    • 谢谢,这将有助于测试场景。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-27
    • 1970-01-01
    相关资源
    最近更新 更多