我不知道我的代码有什么问题,我该怎么解决。
public class ExampleViewModel<T> : ViewModelBase where T : IAppointment
{
private Uri appointmentsSource;
private ObservableCollection<T> appointments;
public ICommand AppointmentCreatedCommand { get; set; }
public Uri AppointmentsSource
{
get { return this.appointmentsSource; }
set { this.appointmentsSource = value; }
}
public ExampleViewModel()
{
this.AppointmentCreatedCommand = new DelegateCommand(OnAppointmentCreatedCommandExecute);
}
private void OnAppointmentCreatedCommandExecute(object obj)
{
var createdAppointment = ((AppointmentCreatedEventArgs)(obj)).CreatedAppointment as Appointment;
ObservableAppointmentCollection apps = System.Windows.Markup.XamlReader.Load(File.OpenRead("../../Appointments.xaml")) as ObservableAppointmentCollection;
apps.Add(createdAppointment);
File.WriteAllText("../../Appointments.xaml", System.Windows.Markup.XamlWriter.Save(apps));
string text = File.ReadAllText("../../Appointments.xaml");
text = text.Replace("<Appointment.TimeZone><s:TimeZoneInfo /></Appointment.TimeZone>", " ");
File.WriteAllText("../../Appointments.xaml", text);
}
public ObservableCollection<T> Appointments
{
get
{
if (this.appointments == null)
{
this.appointments = new ObservableCollection<T>(LoadAppointmentsSource(this.AppointmentsSource));
}
return this.appointments;
}
}
protected static IEnumerable<T> LoadAppointmentsSource(Uri appointmentsSource)
{
if (appointmentsSource != null)
{
IEnumerable<T> appointments = Application.LoadComponent(appointmentsSource) as IEnumerable<T>;
return appointments;
}
return Enumerable.Empty<T>();
}
private static DateTime GetStart(T a)
{
return a.Start.Date;
}
}
XAML
<i:Interaction.Triggers>
<i:EventTrigger EventName="AppointmentCreated">
<i:InvokeCommandAction Command="{Binding AppointmentCreatedCommand, Mode=TwoWay}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
出现错误
NullReferenceException未被用户代码
处理对象引用未设置为对象的实例。
on
var createdAppointment = ((AppointmentCreatedEventArgs)(obj)).CreatedAppointment as Appointment;
每当我在RadScheduleView
(Telerik)中创建约会时,应该创建约会,然后将其写入Appointments.xaml
。
答案 0 :(得分:1)
在您的命令中查看您的XAML以及您使用的类型,我认为您会混淆命令和事件。
命令是一种在单个预定动作上执行方法的方法,通常按下按钮(通常通过点击,敲击或按键),而事件是对象对各种条件作出反应的一种方式。通常,事件会暴露许多事件,而用户控件上只能有一个命令。
现在,这里的最大区别在于,在事件中,发件人填充并传递eventArgs
对象,其中包含触发事件的情况的详细信息。至于命令,这不会发生。可以将参数传递给将在触发时处理命令执行的方法,但您必须自己选择该对象。选择要传递的对象的方式是通过数据绑定,非常类似于绑定Command
本身,但使用CommandParameter
属性而不是Command
。
CommandParameter="{Binding ...}"
答案 1 :(得分:0)
在这一行:
var createdAppointment = ((AppointmentCreatedEventArgs)(obj)).CreatedAppointment as Appointment;
检查obj和CreatedAppointment中的空值。看起来他们中的任何一个都没有设置它们的值。