0

我有一个场景,组合框可以具有相同的字符串值。对于 exa 组合框可以在下拉列表中有以下值:“Test”、“Test1”、“Test1”、“Test1”、“Test2”、

在选定索引的基础上,我正在填充另一个组合框。我的 Xaml 看起来像:

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

ViewModel 看起来像:

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 不会被解雇,因为我在相同的字符串值之间感到困惑(比如将值从索引 1 处的“Test1”更改为索引 2 处的“Test1”。

4

2 回答 2

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}"/ >

所以你不必关心任何索引,因为你已经建立了你的关系。

于 2012-06-13T07:30:47.993 回答
0

而不是绑定到 a 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}"/ >  

这对我有用。

于 2012-06-13T06:51:47.873 回答