如何将Observablecollection绑定到GridView?

时间:2018-07-27 20:49:56

标签: c# xaml uwp observablecollection

我正在开发一个选择图像并将其添加到Observablecollection的应用程序。我想在Xaml中显示此集合。到目前为止,我还没有找到可以理解的明确答案。

在主页上:

public ObservableCollection<TimerWallpaper> timerWallpapers = new ObservableCollection<TimerWallpaper>();

然后其类的代码是这样的:

public class TimerWallpaper
{
    public string timerFileName;
    public BitmapImage timerImgSource;
    public string timerTime;
    public TimerWallpaper(string name, BitmapImage imgSource, int hours, int mins)
    {
        this.timerFileName = name;
        this.timerImgSource = imgSource;
        this.timerTime = hours.ToString() + " : " + mins.ToString();
    }
}

到此为止,似乎代码正在工作..障碍在于此代码:

<GridView ItemsSource="x:Bind timerWallpapers">
  <GridView.ItemTemplate>
    <DataTemplate x:DataType="local:TimerWallpaper">
      <Image Height="100" Width="100" Source="x:Bind timerImgSource"/>
      <TextBlock Text="{x:Bind timerFileName}"/>
      <TextBlock Text="{x:Bind timerTime}"/>
    </DataTemplate>
  </GridView.ItemTemplate>
</GridView>

我一直在获取数据模板元素的“无效值”。 将GridView绑定到集合有什么要求? 正确的格式是什么?

1 个答案:

答案 0 :(得分:2)

好的,您的代码有很多问题。首先,您应该绑定属性,而不是字段,因此您的MainPage.cs应该看起来像这样:

public sealed partial class MainPage : Page
{
    public ObservableCollection<TimerWallpaper> TimerWallpapers { get; set; }

    public MainPage()
    {
        this.InitializeComponent();
        TimerWallpapers = new ObservableCollection<TimerWallpaper>();
        DataContext = this;
    }
}

和您的TimerWallpaper如下:

public class TimerWallpaper
{
    public string TimerFileName { get; set; }
    public BitmapImage TimerImgSource { get; set; }
    public string TimerTime { get; set; }

    public TimerWallpaper(string name, BitmapImage imgSource, int hours, int mins)
    {
        this.TimerFileName = name;
        this.TimerImgSource = imgSource;
        this.TimerTime = hours.ToString() + " : " + mins.ToString();
    }
}

(或根据需要使用私有集)

接下来,您的绑定语法在几行上是错误的,您忘记将其用大括号括起来,最后,DataTemplate只能有一个孩子,因此您需要将UI元素包装在布局,例如StackPanel,就像这样:

<GridView ItemsSource="{x:Bind TimerWallpapers}">
    <GridView.ItemTemplate>
        <DataTemplate x:DataType="local:TimerWallpaper">
            <StackPanel>
                <Image Height="100" Width="100" Source="{x:Bind TimerImgSource}"/>
                <TextBlock Text="{x:Bind TimerFileName}"/>
                <TextBlock Text="{x:Bind TimerTime}"/>
            </StackPanel>
        </DataTemplate>
    </GridView.ItemTemplate>
</GridView>
相关问题