当你填充另一个时,自动添加一个组合框

时间:2013-12-04 15:10:01

标签: c# wpf combobox

您好我需要制作一个程序,您必须通过从组合框中选择它们,将未定义数量的元素添加到列表中。我计划使用4个基本的组合框,当用户从最后一个中选择一个元素时,程序应该在最后一个下自动添加另一个元素(我想使用堆栈面板)。 我怎么办?

感谢。

我的XAML:

<StackPanel Name="listPanel" Grid.Column="0" Margin="10">
                        <Label Content="Example" FontWeight="Bold" HorizontalAlignment="Center"/>
                        <ComboBox Name="ex1Combobox" Margin="0,10,0,0"
                                  ItemsSource="{Binding ExList, Mode=TwoWay}"
                                  SelectedValue="{Binding SelectedEx}" 
                                  DisplayMemberPath="Name" 
                                  SelectedValuePath="ID"/>
                        <ComboBox Name="ex2Combobox" Margin="0,10,0,0"
                                  ItemsSource="{Binding ExList, Mode=TwoWay}"
                                  SelectedValue="{Binding SelectedEx}" 
                                  DisplayMemberPath="Name" 
                                  SelectedValuePath="ID"/>
                        <ComboBox Name="ex3Combobox" Margin="0,10,0,0"
                                  ItemsSource="{Binding ExList, Mode=TwoWay}"
                                  SelectedValue="{Binding SelectedEx}" 
                                  DisplayMemberPath="Name" 
                                  SelectedValuePath="ID"/>
                    </StackPanel>

1 个答案:

答案 0 :(得分:1)

这是你应该使用MVVM的一个很好的例子。

<强>模型

只有像

这样的选定值集合
public class MyChoices
{
  public IEnumerable<string> Selections {get; set;}
}

<强>视图模型

一旦您修改最后一项

,该集合就会延伸
public class MyChoicesViewModel
{
   public MyChoicesViewModel()
   {
     Selections = new ObservableCollection<ChoiceViewModel>();

     //Add first empty value
     AddNewItem();

     Selections.CollectionChanged += (sender, e) => 
     {
       // If you change the last add another
       if (e.NewItems.Contains(Selections.Last()))
         AddNewItem();

     }; 
   }

   public ObservableCollection<ChoiceViewModel> Selections {get; private set;}

   public void AddNewItem()
   {
     var newItem = new ChoiceViewModel();
     Selections.Add(newItem);
     newItem.PropertyChanged += () => 
      {
        //This is where we update the model from the ViewModel
        Model.Selections = from x in Selections
          select x.Value;
      }
    }
}

public class ChoiceViewModel : INotifyPropertyChanged
{
   private string _chosen;
   public string Chosen 
   {
     get { return _chosen; }
     set { 
           if (_chosen != value)
           {
             _chose = value;
             OnPropertyChanged();
           }
         }
    }
    public void OnPropertyChanged([CallerMemberName] string property)
    {
      var temp = PropertyChanged;
      if (temp != null)
      {
        temp(this, new PropertyChangedEventArgs(property));
      }
    }
 }
}

查看                      

<!-- Then show many of them-->
<ListBox ItemsSource="{Binding Selections}"/>