画面に表示させるデータをコードで生成する
画面に表示させるデータを作成するため、xamSchedule_WPF プロジェクトに新しいフォルダーを “ViewModels” と名付け作成し、そのフォルダー内に新しいクラスを “MainWindowViewModel.cs” と名付け、作成します。

このクラスの実装は前回の MainPageViewModel.cs クラスとまったく同じものを流用可能です。
using ScheduleDataViewModel;
using System.Collections.ObjectModel;
using System;
namespace xamSchedule_WPF.ViewModels
{
public class MainWindowViewModel : ViewModelBase
{
#region プロパティ
private ObservableCollection<ResourceInfo> _resources;
public ObservableCollection<ResourceInfo> Resources
{
get { return _resources; }
set
{
_resources = value;
OnPropertyChanged("Resources");
}
}
private ObservableCollection<ResourceCalendarInfo> _resourceCalendars;
public ObservableCollection<ResourceCalendarInfo> ResourceCalendars
{
get { return _resourceCalendars; }
set
{
_resourceCalendars = value;
OnPropertyChanged("ResourceCalendars");
}
}
private ObservableCollection<AppointmentInfo> _appointments;
public ObservableCollection<AppointmentInfo> Appointments
{
get { return _appointments; }
set
{
_appointments = value;
OnPropertyChanged("Appointments");
}
}
private string _currentUserId;
public string CurrentUserId
{
get { return _currentUserId; }
set
{
_currentUserId = value;
OnPropertyChanged("CurrentUserId");
}
}
#endregion
// 省略
}
}
次にコンストラクタを実装します。今回の記事ではコードでデータを作成します。ここでの注意点としては、予定の開始時刻、終了時刻は世界標準時であるということです。
using ScheduleDataViewModel;
using System.Collections.ObjectModel;
using System;
namespace xamSchedule_WPF.ViewModels
{
public class MainWindowViewModel : ViewModelBase
{
#region プロパティ
// 省略
#endregion
#region コンストラクタ
public MainWindowViewModel()
{
// リソースを作成
Resources = new ObservableCollection<ResourceInfo>();
Resources.Add(new ResourceInfo()
{
Id = "R0001",
PrimaryResourceCalendarId = "C0001"
});
// リソースカレンダーを作成
ResourceCalendars = new ObservableCollection<ResourceCalendarInfo>();
ResourceCalendars.Add(new ResourceCalendarInfo()
{
Id = "C0001",
OwningResourceId = "R0001"
});
// 予定を追加
Appointments = new ObservableCollection<AppointmentInfo>();
Appointments.Add(new AppointmentInfo()
{
Id = "A0001",
OwningCalendarId = "C0001",
OwningResourceId = "R0001",
Start = DateTime.Now.ToUniversalTime(),
End = DateTime.Now.AddHours(2).ToUniversalTime(),
});
// 現在のユーザー ID を指定
this.CurrentUserId = this.Resources[0].Id;
}
#endregion
}
}
この MainWindowViewModel を実行時に MainWindow の DataContext に格納します。そのため、MainWindow.xaml.cs を開き、コンストラクタで MainWindowViewModel のインスタンスを作成します。
using System.Windows;
using xamSchedule_WPF.ViewModels;
namespace xamSchedule_WPF
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
MainWindowViewModel vm = new MainWindowViewModel();
this.DataContext = vm;
}
}
}
これでスケジュールに表示させるためのデータの作成が完了しました。

