c#对象引用没有设置为对象的实例
本文关键字:对象 实例 设置 对象引用 | 更新日期: 2023-09-27 18:16:18
我不知道我的代码出了什么问题,我该如何解决。
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未被用户代码处理
对象引用未设置为对象的实例。
var createdAppointment = ((AppointmentCreatedEventArgs)(obj)).CreatedAppointment as Appointment;
每次我在RadScheduleView
(Telerik)中创建约会时,它应该创建约会然后将其写入Appointments.xaml
。
查看您的XAML和您在命令中使用的类型,我认为您混淆了Commands和Events。
命令是在一个预定动作上执行方法的一种方式,通常是点击按钮(通常是通过点击,点击或按键),而事件是对象对各种条件做出反应的一种方式。事件通常会暴露许多事件,而在一个用户控件上只能有一个命令。
现在,这里最大的区别是,在事件上,发送方填充并传递一个eventArgs
对象,其中包含触发事件的情况的性质的详细信息。至于命令,这不会发生。可以将参数传递给方法,该方法将在触发时处理命令的执行,但您必须自己选择该对象。选择要传递的对象的方式是通过数据绑定,很像Command
本身的绑定,但是使用CommandParameter
属性而不是Command
。
CommandParameter="{Binding ...}"
这一行:
var createdAppointment = ((AppointmentCreatedEventArgs)(obj)).CreatedAppointment as Appointment;
检查obj和CreatedAppointment中的空值。看起来它们中的任何一个都没有设置它们的值