xaml - 在 FlipView 中显示绑定数据
问题描述
我已经在 XAML 中声明了一个 FlipView 控件,并且我想将它绑定到在代码后面(.cs 文件)中定义和填充的集合源。此外,texblock 用于显示集合中项目的特定属性。
FlipView 的 XAML 声明:
<FlipView x:Name="FlipViewStudents" Grid.Row="1" Height="Auto" Width="Auto" ItemsSource="{x:Bind Students}">
<FlipView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock x:Name="StudentName" Text="{Binding Name}" FontSize="60" Foreground="Green" FontWeight="Bold" TextAlignment="Left"/>
</StackPanel>
</DataTemplate>
</FlipView.ItemTemplate>
</FlipView>
集合变量的 C# 代码隐藏(属于此 XAML 文件的 .cs 文件)定义:
private List<SingleStudent> Students { get; set; }
更新: 我在 Page_Loaded 事件处理程序中初始化集合变量:
Students = new List<SingleStudent>();
此外,我正在使用具有 30 秒滴答间隔的 DispatcherTimer,并且我在 dispatcherTimer_Tick (发生滴答时)处理程序中填充集合变量(先清除它之后):
Students.Clear();
var singleStudent = new SingleStudent()
{
Name = "John",
Grade = "B"
};
Students.Add(singleStudent);
如图所示,collection 变量每 30 秒被清除和填充一次。我希望 GUI 中的 FlipView 能够在将项目添加到集合时自行更新。
我已经调试并检查了对象是否已在代码中添加到集合中,但它在 GUI 中没有出现任何内容。
如图所示,SingleStudent 是一个具有不同属性的类,包括 Name,它是在 FlipView 中显示的项目属性。
我也尝试过使用 ObservableCollection,但这也不会显示任何内容。帮助或提示表示赞赏。
解决方案
正如您所提到的ListView
,在使用 aList<SingleStudent>
或ObservableCollection<SingleStudent>
我做了一些测试,结果证明在Page_Loaded
事件中初始化集合会弄乱你的数据绑定。因此,您应该定义:
private ObservableCollection<SingleStudent> Students = new ObservableCollection<SingleStudent>();
或者
private ObservableCollection<SingleStudent> Students { get; set; }
public TestPage() //Constructor of your page
{
Students = new ObservableCollection<SingleStudent>();
}
此外,您看到我使用ObservableCollection<SingleStudent>
. 您必须使用它而不是列表。使用 aList<SingleStudent>
将不起作用,因为添加项目不会引发INotifyPropertyChanged
因此不更新数据绑定。
推荐阅读
- filesystems - EFI 应用程序错误写保护
- java - IAnnotation 转换方法不会禁用 testng 中的测试
- typescript - 如果缺少构造函数参数,则不会出错
- xamarin.forms - Xamarin 表单:epubreader NuGet 包的问题
- swift - 带滑块的表格视图
- php - 从多维数组php中完全删除重复项
- reactjs - 如何更改材质 ui 粘性标题表中的颜色?
- unit-testing - 在 ForEach 方法中使用短动作调用语法时不调用 Moq
- amazon-web-services - 使用 bitbucket 作为源时,Terraform 无法从模块中获取参数
- c - C中实用的延续传递风格?