How do ObservableCollection and edit it?



  • Here's a piece of the code to clarify what's going on. This is where I evaporated the schedule from the site, and I can't process it, and there's got to be a class cell to replace the P and L indexes. Please give me a simple example of processing the information through ObservableCollection.

    /// <summary>
    /// Метод получение таблиц с расписанием
    /// </summary>
    /// <param name="facult">Передаем в метод ссылку на выбранный факультет</param>
    /// <param name="groupNumber">передаем в метод ссылку на расписание выбранной группы</param>
    private void GetDatafromSite(string facult, string groupNumber)
    {
        HtmlWeb website = new HtmlWeb();
        HtmlDocument htmlDoc = website.Load(string.Format("https://timetable.tusur.ru/faculties/{0}/groups/{1}", facult, groupNumber));
    
    // There are various options, set as needed
    htmlDoc.OptionFixNestedTags = true;
    
    // Use:  htmlDoc.LoadHtml(xmlString);  to load from a string (was htmlDoc.LoadXML(xmlString)
    // ParseErrors is an ArrayList containing any errors from the Load statement
    if (htmlDoc.ParseErrors != null &amp;&amp; htmlDoc.ParseErrors.Count() &gt; 0) {
        // Handle any parse errors as required
    } else {
        if (htmlDoc.DocumentNode != null) {
            HtmlAgilityPack.HtmlNode bodyNode = htmlDoc.DocumentNode.SelectSingleNode("//body");
            if (bodyNode != null) {
                // Парсим таблицу с расписанием по четным и не четным неделям
                var tables = bodyNode.SelectNodes("//table[contains(@class,'table-lessons')]");
    
                this._firstWeekTimetable = new List&lt;TimetableRowModel&gt;();
                this._secondWeekTimetable = new List&lt;TimetableRowModel&gt;();
    
                this.ParseTable(this._firstWeekTimetable, tables.First());
                this.ParseTable(this._secondWeekTimetable, tables.Last());
    
                this._timetable = new ObservableCollection&lt;TimetableRowModel&gt;(this._firstWeekTimetable);
    
                if (!this.Dispatcher.CheckAccess()) {
                    Application.Current.Dispatcher.Invoke(new Action(() = &gt;
                    {
                        this.SelectGroupStackPanel.Visibility = Visibility.Hidden;
                        this.TimeTableStackPanel.Visibility = Visibility.Visible;
                        this.dgTimetable.DataContext = this._timetable;
                        this.btnOne.IsEnabled = true;
                        this.btnTwo.IsEnabled = true;
                        this.NameTiming.Content = string.Format("{1} -&gt; гр. {0}", selectedGroup, selectedFacultFull);
                    }));
                } else {
                    this.SelectGroupStackPanel.Visibility = Visibility.Hidden;
                    this.TimeTableStackPanel.Visibility = Visibility.Visible;
                    this.dgTimetable.DataContext = this._timetable;
                    this.btnOne.IsEnabled = true;
                    this.btnTwo.IsEnabled = true;
                }
    
                this.week = Week.Odd;
            }
        }
    }
    

    }

    private string TranslitWord(string word)
    {
    return StringHelper.GetTranslit(word).ToUpper();
    }

    private void ParseTable(IList<TimetableRowModel> collection, HtmlNode table)
    {
    var lessons = table.SelectNodes(".//tbody//tr");

    foreach(var lesson in lessons)
    {
        var model = new TimetableRowModel();
        var tds = lesson.SelectNodes(".//td|th");
    
        model.Time = tds[0].InnerText.Trim().Replace(" ", string.Empty);
        model.Day1 = this.ParseDay(tds[1]);
        model.Day2 = this.ParseDay(tds[2]);
        model.Day3 = this.ParseDay(tds[3]);
        model.Day4 = this.ParseDay(tds[4]);
        model.Day5 = this.ParseDay(tds[5]);
        model.Day6 = this.ParseDay(tds[6]);
    
        collection.Add(model);
    }
    
    collection.Add(new TimetableRowModel
    {
        Day1 = string.Empty,
            Day2 = string.Empty,
            Day3 = string.Empty,
            Day4 = string.Empty,
            Day5 = string.Empty,
            Day6 = string.Empty
    });
    

    }

    private string ParseDay(HtmlNode td)
    {
    var result = new StringBuilder();
    var forPrint = td.SelectSingleNode(".//div[contains(@class, 'for_print')]");

    if (forPrint != null) {
        result.AppendLine(forPrint.SelectSingleNode(".//span[contains(@class, 'discipline')]").InnerText);
    
        result.AppendLine(forPrint.SelectSingleNode(".//span[contains(@class, 'kind')]").InnerText);
    
        result.AppendLine(forPrint.SelectSingleNode(".//span[contains(@class, 'auditoriums')]").InnerText);
    
        result.AppendLine(forPrint.SelectSingleNode(".//span[contains(@class, 'group')]").InnerText);
    }
    
    return result.ToString().Trim();
    

    }



  • If dataGrid has to tie the list and properties of the elements of this list, the ObservableCollection should be replaced by BindingList.
    The example of DataGrid is linked to a collection, which is tamerized by adding elements, with each element changing its meaning in time. All changes are made to DataGrid.

    <Window x:Class="WpfApplication1.MainWindow"
                        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                        Title="MainWindow" Height="350" Width="525">
        <DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False" >
            <DataGrid.Columns>
                <DataGridTextColumn Header="Values" Binding="{Binding Value}" />
            </DataGrid.Columns>
        </DataGrid>
    </Window>
    

    using System;
    using System.ComponentModel;
    using System.Windows;
    using System.Windows.Threading;
    namespace WpfApplication1 {
        public partial class MainWindow : Window {
            public MainWindow() {
                InitializeComponent();
                var c = new BindingList<Data>();
                this.DataContext = c;
                // по таймеру добавляем элементы в коллекцию
                var t = new DispatcherTimer() { Interval = TimeSpan.FromSeconds(1) };
                t.Tick += (s, e) => {
                    if (c.Count >= 10) t.Stop();
                    c.Add(new Data());
                };
                t.Start();
            }
        }
        public class Data : INotifyPropertyChanged {
            public event PropertyChangedEventHandler PropertyChanged = delegate { };
            System.Timers.Timer t;
            static Random r = new Random();
            public Data() {
                // по таймеру меняем значение свойства Value 
                t = new System.Timers.Timer() { Interval = r.Next(500, 1000) };
                t.Elapsed += (s, e) => {
                    Value = DateTime.Now.Ticks;
                    this.PropertyChanged(this, new PropertyChangedEventArgs("Value"));
                };
                t.Start();
            }
            public long Value { get; private set; }
        }
    }
    



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2