Разделить полную сетку данных на однодневные таблицы данных в C # WPF - PullRequest
0 голосов
/ 01 октября 2018

Я создаю небольшое приложение, которое просто регистрирует комментарии пользователей и сохраняет этот комментарий, добавляя дату и имя пользователя.

Прямо под моим полем для ввода комментариев я хочу показать последние регистрации.В общем, я получил то, что мне нужно в этом коде:

<Window x:Class="OperationHelper.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:OperationHelper"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid Margin="5,30,5,30">
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"  />
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid Grid.Row="0" FocusManager.FocusedElement="{Binding ElementName=RegistrationTextBox}">
            <Grid Margin="0,0,0,10" Grid.Row="1">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="100"/>
                        <ColumnDefinition Width="*"/>
                        <ColumnDefinition Width="50"/>
                    </Grid.ColumnDefinitions>
                    <DatePicker Grid.Column="0" ></DatePicker>
                    <TextBox Grid.Column="1" Name="RegistrationTextBox"  />
                <Button Grid.Column="2" Content="OK" />
            </Grid>
        </Grid>
        <DataGrid Grid.Row="1" Name="LatestRegiDataGrid" ItemsSource="{Binding}"  AutoGenerateColumns="False" >
            <DataGrid.Columns>
                <DataGridTextColumn Header="Date" Binding="{Binding Path=TimeStamp, StringFormat=\{0:yyyy.MM.dd HH:mm:ss\}}" />
                <DataGridTextColumn Header="Who" Binding="{Binding Path=Person}" />
                <DataGridTextColumn Header="Comment" Binding="{Binding Path=Comment}" Width="*"/>
            </DataGrid.Columns>

        </DataGrid>
    </Grid>
</Window>

enter image description here

Но затем я начинаю становиться разборчивым.

Я хотел бы разбить свою сетку данных на под-сетки данных, которые содержат только отдельные дни.

Мне это нужно, потому что я хотел бы вставить плитку между этими днями.Вот макет картинки: enter image description here

Вот мой класс данных:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OperationHelper
{
    class Registration
    {
        public Registration(DateTime TS, String P, String C)
        {
            TimeStamp = TS;
            Person = P;
            Comment = C;
        }


        public DateTime TimeStamp { get; set; }
        public String Person { get; set; }
        public String Comment { get; set; }
    }
}

А вот мой класс обработчика данных:

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualBasic.FileIO;


namespace OperationHelper
{
    class RegistrationHandler
    {
        private DateTime FirstDateOfWeekISO8601(int year, int weekOfYear)
        {
            DateTime jan1 = new DateTime(year, 1, 1);
            int daysOffset = DayOfWeek.Thursday - jan1.DayOfWeek;

            // Use first Thursday in January to get first week of the year as
            // it will never be in Week 52/53
            DateTime firstThursday = jan1.AddDays(daysOffset);
            var cal = CultureInfo.CurrentCulture.Calendar;
            int firstWeek = cal.GetWeekOfYear(firstThursday, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);

            var weekNum = weekOfYear;
            // As we're adding days to a date in Week 1,
            // we need to subtract 1 in order to get the right date for week #1
            if (firstWeek == 1)
            {
                weekNum -= 1;
            }

            // Using the first Thursday as starting week ensures that we are starting in the right year
            // then we add number of weeks multiplied with days
            var result = firstThursday.AddDays(weekNum * 7);

            // Subtract 3 days from Thursday to get Monday, which is the first weekday in ISO8601
            return result.AddDays(-3);
        }

        private DateTime LastDateOfWeekISO8601(int year, int weekOfYear)
        {
            DateTime jan1 = new DateTime(year, 1, 1);
            int daysOffset = DayOfWeek.Thursday - jan1.DayOfWeek;

            // Use first Thursday in January to get first week of the year as
            // it will never be in Week 52/53
            DateTime firstThursday = jan1.AddDays(daysOffset);
            var cal = CultureInfo.CurrentCulture.Calendar;
            int firstWeek = cal.GetWeekOfYear(firstThursday, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);

            var weekNum = weekOfYear;
            // As we're adding days to a date in Week 1,
            // we need to subtract 1 in order to get the right date for week #1
            if (firstWeek == 1)
            {
                weekNum -= 1;
            }

            // Using the first Thursday as starting week ensures that we are starting in the right year
            // then we add number of weeks multiplied with days
            var result = firstThursday.AddDays(weekNum * 7);

            // Subtract 3 days from Thursday to get Monday, which is the first weekday in ISO8601
            return result.AddDays(3);
        }

        private List<Registration> RegistrationList = new List<Registration>();

        public void LoadData(string DataSource)
        {
            using (TextFieldParser csvParser = new TextFieldParser(DataSource))
            {
                csvParser.CommentTokens = new string[] { "#" };
                csvParser.SetDelimiters(new string[] { ";" });
                csvParser.HasFieldsEnclosedInQuotes = false;

                // Skip the row with the column names
                csvParser.ReadLine();

                while (!csvParser.EndOfData)
                {
                    // Read current line fields, pointer moves to the next line.
                    string[] fields = csvParser.ReadFields();
                    DateTime Date = DateTime.Parse(fields[0]);
                    string Person = fields[1];
                    string Comment = fields[2];

                    RegistrationList.Add(new Registration(Date, Person, Comment));
                }
            }
        }

        public List<Registration> GetRegistrationPerioed(int StartWeek, int EndWeek = 0)
        {
            if (EndWeek == 0) { EndWeek = StartWeek; }
            DateTime firstDateOfStartWeek = FirstDateOfWeekISO8601(DateTime.Now.Year, StartWeek);
            DateTime lastDateOfEndWeek = LastDateOfWeekISO8601(DateTime.Now.Year, EndWeek);

            List<Registration> scopedRegistrationList = new List<Registration>();

            foreach (Registration regi in RegistrationList)
            {
                if(regi.TimeStamp >= firstDateOfStartWeek && regi.TimeStamp <= lastDateOfEndWeek) { scopedRegistrationList.Add(regi); }
            }

            return scopedRegistrationList;
        }

        public List<Registration> GetLatestRegistrations(int Days)
        {
            List<Registration> scopedRegistrationList = new List<Registration>();


            foreach (Registration regi in RegistrationList)
            {
                if (regi.TimeStamp >= DateTime.Today.AddDays(-1 * Days)) { scopedRegistrationList.Add(regi); }
            }



            List<Registration> sortedScopedRegistrationList = scopedRegistrationList.OrderBy(o => o.TimeStamp).ToList();


            return sortedScopedRegistrationList;
        }

    }
}

и мой основной

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Configuration;

namespace OperationHelper
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            var csvDataFile = GetAppSettings().Get("CSVDataFile");
            int DataDays = int.Parse(GetAppSettings().Get("DefaultDataDays")) -1;


            var regHandler = new RegistrationHandler();
            regHandler.LoadData(csvDataFile);
            List<Registration> scopedRetroData = regHandler.GetRegistrationPerioed(38,39);
            List<Registration> scopedLatestData = regHandler.GetLatestRegistrations(DataDays);


            LatestRegiDataGrid.DataContext = scopedLatestData;

            //LatestRegsListBox.ItemsSource = scopedLatestData;


        }

        private static System.Collections.Specialized.NameValueCollection GetAppSettings()
        {
            return ConfigurationSettings.AppSettings;
        }
    }
}

Я думаю, что это вопрос обработки данных, получения данных в виде набора «дней», а затем начала строить wpf вокруг этих наборов данных.

как бывы, ребята, подходите к этому?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...