You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用CalendarView筛选日记类记录条目?新手技术求助

实现CalendarView点击日期展示当日记录的步骤

1. 给CalendarView绑定日期选择事件

先找到界面里的CalendarView控件,给它加上日期选择变化的事件处理。比如在XAML里直接写:

<CalendarView SelectedDatesChanged="CalendarView_SelectedDatesChanged"/>

2. 写个方法读取并筛选当日记录

每次点选日期时,需要读取你的TXT文件,拆分每条记录的时间戳和内容,然后挑出和选中日期匹配的记录。假设你的TXT每条格式是2024-05-21 14:30:00 | 记录内容,可以这么写:

using System.IO;
using System.Collections.Generic;
using System.Globalization;

private List<string> GetDailyRecords(DateTime targetDate)
{
    var dailyRecords = new List<string>();
    // 替换成你的TXT文件实际路径,比如@"C:\MyNotes.txt"
    string filePath = @"你的记录文件路径";

    if (File.Exists(filePath))
    {
        foreach (var line in File.ReadAllLines(filePath))
        {
            // 拆分时间戳和内容,解析时间
            var parts = line.Split('|');
            if (parts.Length >= 2 && DateTime.TryParseExact(parts[0].Trim(), "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime recordTime))
            {
                // 只匹配年月日,忽略时分秒
                if (recordTime.Date == targetDate.Date)
                {
                    dailyRecords.Add(line);
                }
            }
        }
    }
    return dailyRecords;
}

3. 在事件里展示筛选后的记录

回到CalendarView的事件处理方法,调用上面的方法,把结果绑定到ListView或者文本块:

  • 如果用ListView(假设控件名叫lvDailyRecords):
private void CalendarView_SelectedDatesChanged(object sender, CalendarViewSelectedDatesChangedEventArgs e)
{
    if (e.AddedDates.Count > 0)
    {
        DateTime selectedDate = e.AddedDates[0].Date;
        lvDailyRecords.ItemsSource = GetDailyRecords(selectedDate);
    }
}
  • 如果用文本块(假设控件名叫txtDailyRecords):
private void CalendarView_SelectedDatesChanged(object sender, CalendarViewSelectedDatesChangedEventArgs e)
{
    if (e.AddedDates.Count > 0)
    {
        DateTime selectedDate = e.AddedDates[0].Date;
        var records = GetDailyRecords(selectedDate);
        txtDailyRecords.Text = string.Join(Environment.NewLine, records);
    }
}

新手注意点

  • 记得在代码顶部加using System.IO;和using System.Collections.Generic;,不然相关类用不了。
  • 如果你的时间戳格式和示例不一样,要调整DateTime.TryParseExact里的格式字符串,比如你的时间是2024/05/21,就把格式改成"yyyy/MM/dd"。
  • 测试时可以先把TXT文件放在程序的输出目录(比如bin/Debug文件夹),避免路径错误。

内容的提问来源于stack exchange,提问作者therealchriswoodward

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 01:10:29