首页 > 解决方案 > 如何将 Observablecollection 绑定到 GridView?

问题描述

我正在开发一个选择图像并将它们添加到 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 绑定到集合有什么要求?这样做的正确格式是什么?

标签: c#xamluwpobservablecollection

解决方案


好的,您的代码存在许多问题。首先,你应该绑定到属性,而不是字段,所以你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 元素包装在布局中,例如 a 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>

推荐阅读