C# 组合框绑定时出现NullReferenceException
我有一个投递箱:C# 组合框绑定时出现NullReferenceException,c#,wpf,xaml,C#,Wpf,Xaml,我有一个投递箱: <ComboBox Height="23" Name="DriveSelection" Width="120" ItemsSource="{Binding Path=FixedDrives}" DisplayMemberPath="Name" SelectedItem="{Binding Pat
<ComboBox Height="23" Name="DriveSelection" Width="120"
ItemsSource="{Binding Path=FixedDrives}"
DisplayMemberPath="Name"
SelectedItem="{Binding Path=DriveSelection_SelectionChanged}"
IsSynchronizedWithCurrentItem="True"
IsEnabled="{Binding DriveIsEnabled}"
SelectedValue="{Binding DriveSelected}"
/>
最后一行:
this.driveSelection=新的DriveInfo(this.root)代码>我在此行中获取空引用异常:
private void UpdatePathManager()
{
string newRoot = this.driveSelection.ToString(); <--- this line
//string newRoot = this.page.DriveSelection.SelectedValue.ToString();
}
private void updatePath Manager()
{
字符串newRoot=this.driveSelection.ToString()
固定驱动器
选择改变了
驾驶执照
驾驶选择
并且处理DriveSelected
正在触发'DriveSelection\u SelectionChanged',value=null。这导致了问题。看起来可能是DriveIsEnabled setter(不包括在代码中)正在调用updatePath()。
通过将构造函数更改为以下值,应确保this.driveSelection从不为null:
public PathSelectionPageViewModel(PathSelectionPage _page)
{
this.page = _page;
this.root = Path.GetPathRoot(App.Instance.PathManager.InstallRoot).ToUpperInvariant();
this.driveSelection = new DriveInfo(this.root);
this.DriveSelected = (object)this.root;
//this.page.DriveSelection.SelectedValue = (object)this.root;
this.DriveIsEnabled = true
//this.page.DriveSelection.IsEnabled = true
}
这里真正的问题是使用此代码分配的新DriveInfo(this.root)
this.driveSelection = new DriveInfo(this.root);
不是FixedDevices
集合的一部分。这导致null
通过WPF绑定传递给您的属性
在那之后支票
if (value == this.driveSelection)
在属性DriveSelection\u selection changed
中,由于您已将新的DriveInfo(this.root)
分配给变量DriveSelection
,因此会导致false
检查失败导致driveSelection设置为null,然后在UpdatePath Manager()中抛出NullReferenceException
Stacktrace或它不太可能driveSelection
为null
。因此,请使用调试器查看您是否真的达到了您认为已将其设置为某个值的程度。尝试移动行this.driveSelection=new DriveInfo(this.root);到构造函数的开头,就在this.root=Path.GetPathRoot…UpdatePathManager
被DriveSelection\u SelectionChanged
调用之后,它包含在我的代码段中。无论何时调用,绑定都不会检查此.DriveSelection是否为null,这意味着您需要确保它已设置在触发绑定之前,要执行此操作,只需在构造函数中创建DriveInfo实例,并可能在其上实现INotifyPropertyChange(如果您计划在绑定数据时更改其属性)。我用一些新信息更新了我的问题
this.driveSelection = new DriveInfo(this.root);
if (value == this.driveSelection)