2014-09-02 26 views
0

的價值我有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"); 
     } 
    } 

,你可以看到我綁定hardrives的列表,組合框爲itemSource。然後如果需要,我正在更改此行中的選定項目:

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

例如: this.root指向驅動器E,所以組合框選擇應該改爲E,但現在它仍然掛在C。 我的綁定是錯誤的或錯誤是在其他地方?

+4

'DriveInfo'不會覆蓋'Equals'因此將參照進行比較。從'fixedDrives'列表中選擇一個'DriveInfo',而不是創建新的實例 – dkozl 2014-09-02 08:36:37

+0

您可以發佈一個片段,其中我應該修改我的代碼片段嗎? – szpic 2014-09-02 08:43:49

+0

嘗試類似'this.DriveSelection_SelectionChanged = FixedDrives.FirstOrDefault(d => d.Name == this.Root)' – dkozl 2014-09-02 08:49:13

回答

1

你在這行

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

與新創建的對象不包含在你數據綁定到的ItemsSource的FixedDrivers列表。如果您選擇在FixedDrivers的項目之一右邊的項目將被選中

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