我的应用程序中有多个viewModel,并在ViewModelLocator mvvm light中绑定/使用它们。我在DailyActivities.xaml页面上做了一个按钮。但是当我点击它时,它在ViewModelLocator中给出了错误,例如“对象引用未设置为对象的实例”。和控制来到这一行:
public static void ClearActivities() { _activities.Cleanup(); //这里错误 _activities = null; }
这是ViewModelLocator中DailyActivitiesViewModel的代码:
private static ActivitiesViewModel _activities;
public static ActivitiesViewModel ActivitiesStatic
{
get
{
if (_activities == null)
{
CreateActivities();
}
return _activities;
}
}
/// <summary>
/// Gets the ViewModelPropertyName property.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
"CA1822:MarkMembersAsStatic",
Justification = "This non-static member is needed for data binding purposes.")]
public ActivitiesViewModel Activities
{
get
{
return ActivitiesStatic;
}
}
/// <summary>
/// Provides a deterministic way to delete the ViewModelPropertyName property.
/// </summary>
public static void ClearActivities()
{
_activities.Cleanup(); --Error here
_activities = null;
}
/// <summary>
/// Provides a deterministic way to create the ViewModelPropertyName property.
/// </summary>
public static void CreateActivities()
{
if (_activities == null)
{
_activities = new ActivitiesViewModel();
}
}
请建议?
由于
答案 0 :(得分:1)
在使用之前,您需要确定该字段是否存在:似乎字段_activities已经为null,因此不需要清理。
为什么不做像
这样的事情public static void ClearActivites()
{
if (null == _activities) return;
_activities.Cleanup();
_activities = null;
}