用数组中的日期时间值加载ObservableCollection
本文关键字:加载 ObservableCollection 时间 日期 数组 | 更新日期: 2023-09-27 18:13:56
我在一个名为HistoryStatistics的类中有一个ListView,它的模板看起来像这样。每个项目都有一个按钮和两个文本块。
<ListView x:Name="HistoryLV" Grid.Row="1" Grid.Column="1" Margin="20,20,20,20">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Button/>
<TextBlock x:Name="historyDatesTBlock" Text="{Binding}" Foreground="Coral"/>
<TextBlock x:Name="cycleLengthTBlock" Foreground="AliceBlue"/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
现在我需要用两个不同的值绑定文本框。我有一个叫做CycleManager的类。它有一个DateTime数组。我想将数组的前n个值绑定到第一个文本块。
在HistoryStatistics的构造函数中,我有一个名为LoadListView的函数。
public void LoadListView()
{
CycleManager cycMan = CycleManager.Instance;
DateTime[] items = cycMan.GetHistoryArray();
HistoryList = new ObservableCollection<DateTime>(items);
HistoryLV.DataContext = HistoryList;
}
这是绑定DateTime的正确方式吗?我尝试添加ToString,但没有显示日期。
是否有一种方法,你可以在代码后面创建一个ListView,并通过运行forloop将单个项目与我想要的值绑定?
请尝试将以下行添加到您的LoadListView方法中。我自己没有尝试过,因为我的系统上没有安装Windows 8。
HistoryLV.ItemsSource = HistoryList;
尝试:
CycleManager cycMan = CycleManager.Instance;
DateTime[] items = cycMan.GetHistoryArray();
string[] list = new string[items.Length];
for(int i=0; i<items.Length; i++)
{
list[i] = items[i].ToString("**The DateTime format you want**");
}
HistoryList = new ObservableCollection<string>(list);
HistoryLV.ItemsSource = HistoryList;