绑定不改变Combobox的选定值

时间:2014-09-02 08:32:23

标签: c# wpf mvvm combobox

我有ComboBox

  <ComboBox Height="23" Name="DriveSelection" Width="120"
                              ItemsSource="{Binding Path=FixedDrives}"
                              DisplayMemberPath="Name"
                              SelectedItem="{Binding DriveSelection_SelectionChanged }"
                              IsSynchronizedWithCurrentItem="True"
                              IsEnabled="{Binding DriveIsEnabled}"
                              />

在我的viewModel中,它看起来像这样:

    public PathSelectionPageViewModel(PathSelectionPage _page)
    {
        this.page = _page;
        this.root = Path.GetPathRoot(App.Instance.PathManager.InstallRoot).ToUpperInvariant();
        this.DriveSelection = this.root;
        this.DriveSelection_SelectionChanged = new DriveInfo(this.root);
        this.DriveIsEnabled = App.Instance.PathManager.CanModify;
        this.RunText = App.Instance.InstallationProperties.InstallationScript.Installer.Name;

    }
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");
        }
    }

正如你所看到的那样,我将组合框中的硬件列为itemSource。然后,如果需要,我将更改此行中的所选项目:

this.DriveSelection_SelectionChanged = new DriveInfo(this.root);

EG。 this.root指向驱动器E,因此组合框选择应更改为E,但现在它仍然挂在C。 我的绑定是错误的或错误在别的地方?

1 个答案:

答案 0 :(得分:1)

您在此行使用new创建的对象

this.DriveSelection_SelectionChanged = new DriveInfo(this.root);

未包含在您对ItemsSource进行数据绑定的FixedDrivers列表中。如果您选择FixedDrivers中的一个项目,将选择正确的项目

var selectedItem = this.FixedDrives.FirstOrDefault(d => d.Name == this.Root);
this.DriveSelection_SelectionChanged = selectedItem;