我有一个Dropbox:
<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}"
/>
使用这个绑定:
private ObservableCollection<DriveInfo> fixedDrives;
public ObservableCollection<DriveInfo> FixedDrives
{
get
{
if (this.fixedDrives != null)
return this.fixedDrives;
this.fixedDrives = new ObservableCollection<DriveInfo>(Enumerable.Where<DriveInfo>((IEnumerable<DriveInfo>)DriveInfo.GetDrives(), (Func<DriveInfo, bool>)(driveInfo => driveInfo.DriveType == DriveType.Fixed)));
return this.fixedDrives;
}
}
public DriveInfo DriveSelection_SelectionChanged
{
get
{
return this.driveSelection;
}
set
{
if (value == this.driveSelection)
return;
this.driveSelection = value;
UpdatePathManager();
this.OnPropertyChanged("DriveSelection_SelectionChanged");
}
}
public object DriveSelected
{
get
{
return _driveSelected;
}
set
{
_driveSelected = value;
RaisePropertyChanged("DriveSelected");
}
}
在执行页面初始化时:
public PathSelectionPageViewModel(PathSelectionPage _page)
{
this.page = _page;
this.root = Path.GetPathRoot(App.Instance.PathManager.InstallRoot).ToUpperInvariant();
this.DriveSelected = (object)this.root;
//this.page.DriveSelection.SelectedValue = (object)this.root;
this.DriveIsEnabled = true
//this.page.DriveSelection.IsEnabled = true
this.driveSelection = new DriveInfo(this.root);
}
在最后一行:
this.driveSelection = new DriveInfo(this.root);
,我遇到了空引用异常,在这一行代码中:private void UpdatePathManager()
{
string newRoot = this.driveSelection.ToString(); <--- this line
//string newRoot = this.page.DriveSelection.SelectedValue.ToString();
}
如您所看,我只是试图将来自视图的读取数据直接转换为绑定,但我遇到了问题。 应该改变什么来解决它?
@更新 正如我刚刚发现的: 问题在于处理绑定时。WPF按照以下顺序处理绑定-> 1. 固定驱动器 2. 选择更改 3. 驱动器启用 4. 已选择驱动器
处理`DriveSelected`会触发带有值=null的“DriveSelection_SelectionChanged”,这就导致了问题。
driveSelection
是null
。因此,请使用调试器查看您是否实际上到达了您认为已将其设置为某个值的点。 - Dirk