c# - 如何将 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 绑定到集合有什么要求?这样做的正确格式是什么?
解决方案
好的,您的代码存在许多问题。首先,你应该绑定到属性,而不是字段,所以你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>
推荐阅读
- multithreading - 在 Rust 中的 application.run 之后等待后端线程完成
- ios - 如何将 txt 文件中的数据解析为模型?
- javascript - 了解 ShiftKey 事件属性的 MDN 文档
- python - 我需要在模拟模式下使用 Gekko m.connection 来解决我的代码吗?
- yaml - Github Actions cmd 参数在新行中传递
- dataset - 通过 API 导入超集数据集
- php - 从条带中获取每天所有新客户的记录并存储在 MYSQL 数据库中
- python - GEKKO 的二进制优化
- php - 如何检查数据是否符合方案
- r - 生命表中的间隔