【发布时间】:2016-05-04 01:19:48
【问题描述】:
``我完全不知道为什么会出现此错误:
发生 System.NullReferenceException H结果=-2147467261 Message=对象引用未设置为对象的实例。 源 = Xamarin.Forms.Platform.UAP 堆栈跟踪: 在 Xamarin.Forms.Platform.UWP.WindowsBasePlatformServices.get_IsInvokeRequired() 在 Xamarin.Forms.ListProxy.OnCollectionChanged(对象发件人,NotifyCollectionChangedEventArgs e) 在 Xamarin.Forms.ListProxy.WeakNotifyProxy.OnCollectionChanged(对象发件人,NotifyCollectionChangedEventArgs e) 在 System.Collections.ObjectModel.ObservableCollection
1.OnCollectionChanged(NotifyCollectionChangedEventArgs e) at System.Collections.ObjectModel.ObservableCollection1.InsertItem(Int32 索引,T 项) 在 System.Collections.ObjectModel.Collection`1.Add(T 项) 在 ViewModels.ScanBadgesViewModel.Add(BadgeScan 结果) 内部异常:
错误来自以下行:
EmployeeIds.Add(badge.EmployeeId)
注意: 在 Xamarin.Forms Windows 10 通用应用(预览版)上观察到此错误。
如果我在 XAML 中注释掉 ListView 元素,那么我将不再收到 null 异常。
如果我只注释掉ListView的ItemTemplate,那么我仍然观察到null异常。
XAML:
<Grid Grid.Row="4" Grid.RowSpacing="3" Grid.ColumnSpacing="3" BackgroundColor="Silver">
<ListView ItemsSource="{Binding EmployeeIds}" SelectedItem="{Binding SelectedEmployeeId}"
BackgroundColor="Black">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<Label Text="{Binding Value}" TextColor="Yellow" XAlign="Start" />
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
ViewModel 属性:
ObservableCollection<EmployeeId> _employeeIds = new ObservableCollection<EmployeeId>();
public ObservableCollection<EmployeeId> EmployeeIds
{
get { return _employeeIds; }
set
{
if (_employeeIds != value)
{
_employeeIds = value;
OnNotifyPropertyChanged();
}
}
}
实体:
public class EmployeeId
{
public EmployeeId(string employeeId) { Value = employeeId; }
public string Value { get; }
}
public class BadgeScan
{
public BadgeScan(string employeeId) { EmployeeId = new EmployeeId(employeeId); }
public BadgeScan(BadgeScan source, Predicate<string> validate) : this(source.EmployeeId.Value)
{
IsValid = validate.Invoke(source.EmployeeId.Value);
}
public EmployeeId EmployeeId { get; }
public bool IsValid { get; }
}
更新
这行代码改变了我的 ObservableCollection.Add 操作的行为:
var administeredScan = new BadgeScan(result, validate);
该行只是创建对象的副本。
var validate = DependencyManager.Resolve(typeof(Predicate<string>)) as Predicate<string>;
var administeredScan = new BadgeScan(result, validate);
var canAdd = CanAdd(administeredScan) &&
ScanMode == Entities.ScanMode.Add;
if (canAdd) Add(administeredScan);
break;
即使将一个项目添加到集合中,这仍然会引发异常:
Add(administeredScan);
但是,这成功了:
var result = obj as BadgeScan;
Add(result);
因此,创建要添加到我的 observable 的对象的副本失败。但添加原始对象成功。
【问题讨论】:
标签: xaml win-universal-app xamarin.forms