1

我正在做一个 UWP 应用程序,我很难用 UWP 应用程序加载和绑定图像,应该怎么做?

我目前的结构:

MyApp.Model:
 |
 |-Models
   |-MyModel.cs
   |-MyModelContainer.cs
 |-Resources
   |-image1.png
   |-image2.png
   |-image3.png

我的 Xaml 在另一个项目中(win 10 通用应用程序并引用了这个 Portable 类库。)

MyModelContainer只是一个实例化 a 的单例容器IEnumerable<MyModel>。以下是他们的内容:

public class MyModel{
    public String Name{get;set;}
    public ??????? Icon {get;set;}
}

public static class MyModelContainer{
    private static IEnumerable<MyModel> _myModelList;

    public static IEnumerable<MyModel> MyModelList{get{
        if(_myModelList==null){
            Initialize();
        }
        return _myModelList;
    }}

    private static Initialize(){
        _myModelList = new List<MyModel>() {
            new MyModel(){
                Name = "Model one"
                Icon = ???????
            }
        };
    }
}

在我的 XAML 中的某个地方,我收到一个列表MyModel,其中包含ItemsControl

<ItemsControl  ItemsSource="{Binding MyModelListProperty}"  >
    <ItemsControl.ItemsPanel >
        <ItemsPanelTemplate>
            <StackPanel/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate >
            <Button Margin="10" MinHeight="50" MinWidth="40"  HorizontalAlignment="Stretch" VerticalAlignment="Stretch" >
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="*"></RowDefinition>
                        <RowDefinition Height="Auto"></RowDefinition>
                    </Grid.RowDefinitions>
                    <Image Source="{Binding Icon}" ></Image>
                    <TextBlock Grid.Row="1" Text="{Binding Name}" ></TextBlock>
                </Grid>
            </Button>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>^

我的问题:

  1. 我应该使用什么类型的属性来绑定图像(我认为它是BitmapImage
  2. 我应该如何创建这个属性?我试过Icon = new BitmapImage(new Uri("ms-appx://MyApp.Model/Resources/image1.png"))没有任何运气,我没有加载图像(并且触发了 ImageFailed 事件)。
  3. 我应该如何将此属性绑定到<Image/>

这适用于 UWP(Windows 10)应用程序,而不是 WPF,而不是 win8。

非常感谢。

编辑

这是文件夹结构

MyApp == AstroApp
MyApp.Model == AstroApp.Model
MyModel = AstroSign
MyModelContainer = AstroManager

在此处输入图像描述

4

1 回答 1

3

如果您的图像与 MyModelContainer 位于同一项目中,则应该可以:

public class MyModel{
    public String Name{get;set;}
    public ImageSource Icon {get;set;}
}

public static class MyModelContainer{
    private static IEnumerable<MyModel> _myModelList;

    public static IEnumerable<MyModel> MyModelList{get{
        if(_myModelList==null){
            Initialize();
        }
        return _myModelList;
    }}

    private static Initialize(){
        _myModelList = new List<MyModel>() {
            new MyModel(){
                Name = "Model one"
                Icon = new BitmapImage(new Uri("ms-appx:///Resources/image1.png"));
            }
        };
    }
}

如果您的图像在另一个程序集中,请使用此 url:

Icon = new BitmapImage(new Uri("ms-appx:///NameOfProjectWithImage/Resources/image1.png"));
于 2016-04-18T20:50:33.573 回答