2012-06-13 49 views
0

我有一個組合框可以有相同的字符串值的場景。對於EXA組合框可以有以下的下拉值: 「測試」, 「測試1」, 「測試1」, 「測試1」, 「的Test2」,Wpf的ComboBox沒有觸發SelectedIndex

在選擇指數的基礎上,我填另一個組合框。我的XAML的樣子:

<Grid > 
    <Grid.RowDefinitions> 
     <RowDefinition Height="40"></RowDefinition> 
    </Grid.RowDefinitions> 
    <ComboBox ItemsSource="{Binding Path=ComboList, Mode=OneWay}" 
       SelectedIndex="{Binding Path=ComboIndex, Mode=TwoWay}"/ > 
</Grid> 

視圖模型的樣子:

class TestViewModel : INotifyPropertyChanged 
{ 
    private IList<string> _comboList = new List<string> 
             { 
              "Test", 
              "Test1", 
              "Test1", 
              "Test1", 
              "Test2", 
             };  

    public IList<string> ComboList 
    { 
     get { return _comboList; } 
    } 


    private int _comboIndex; 

    public int ComboIndex 
    { 
     get { return _comboIndex; } 
     set 
     { 
      if (value == _comboIndex) 
      { 
       return; 
      } 

      _comboIndex = value; 
      OnPropertyChanged("ComboIndex"); 
     } 
    } 

    private void OnPropertyChanged(string prop) 
    { 
     if (PropertyChanged != null) 
     { 
      PropertyChanged(this, new PropertyChangedEventArgs(prop)); 
     } 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 
} 

問題,我面對的是,SelectedIndex的不解僱櫃面我相同的字符串值之間suffling(像「Test1的」改變價值,本索引1處,以「測試1」,存在於2

+0

爲什麼不使用SelectedItem? – blindmeis

+0

*我面對的問題是SelectedIndex不會被解僱,因爲我在同一個字符串值*之間成功。這種說法沒有道理。你綁定到索引,這將永遠是不同的。 – McGarnagle

+0

@blindmeis:我正在使用選定的索引,因爲根據selectedindex我需要填充另一個組合框。無論如何,即使SelectedItem或selectedvalue也不會在descibed場景中被解僱。 –

回答

0

代替結合到List<string>,封裝字符串索引,例如

public class Item 
{ 
    public Item(string v){ Value = v; } 
    public string Value{get; private set;} 
} 

並綁定到List<Item>

然後修改XAML中指定的DisplayMemberPath

<ComboBox ItemsSource="{Binding Path=ComboList, Mode=OneWay}" 
      DisplayMemberPath="Value" 
      SelectedIndex="{Binding Path=ComboIndex, Mode=TwoWay}"/ > 

爲我工作。

1

當我需要這樣的關係,我在創建視圖模型我的關係,簡單地綁定到該集合

public class MyItem 
{ 
    public string Name {get; set;}//your Test, Test1, Test1 ... 
    public List<string> Childs {get; set;} // the childs depending on the the Name 
} 

在你的視圖模型您現在可以創建你的MyItem的名單,並像你需要填充它。

public List<MyItem> MyItemList {get;set;} 

XAML中,你現在可以簡單地創建您的相關組合框。

<ComboBox ItemsSource="{Binding Path=MyItemList}" 
      SelectedItem="{Binding Path=ComboIndex, Mode=TwoWay}"/ > 

<ComboBox ItemsSource="{Binding Path=ComboIndex.Childs}" 
      SelectedItem="{Binding Path=MySelectedPropForChild, Mode=TwoWay}"/ > 

所以你不必關心任何索引,因爲你已經建立你的關係。