2012-05-22 74 views
3

我使用C#,WPF并尝试使用MVVM。所以我有一个MyObjects的ObservableCollection。该列表呈现到DataGrid中,MyObject的一个属性是每行中ComboBoxes中显示的静态项目列表。C#WPF组合框 - 允许项目每个列表只能选择一次

现在我想在一排在这个组合框中选择一个项目,如果它是在另一行之前选择,最后选择已被删除默认值。我怎样才能管理这个?我的MyObjectViewModel知道它自己的组合框的变化,但它怎么能告诉MainViewModel(它保存着MyObjects的ObservableCollection)来将最后一个选择的组合框项目从另一个MyObject对象中改变出来?

+0

你说这份清单是静态的,对吧?所以你不应该只能删除选定的项目,它会自动更新所有行? – McGarnagle

+0

我不希望它从列表中删除;如果之前还有另一个与此项目一起选择的ComboBox,则必须删除此ComboBox选择。 – iop

+0

为什么不使用所有项目“AllItems”的列表,一个用于所选项目“SeledtedItems”,第三个项目使用可用项目“AvailableItems”,后者是“AllItems”减去“SelectedItems”的计算。该列表是您绑定到ComboBoxes的ItemsSource的列表。 每当“SelectedItems”更改时,都会在“AvailableItems”上触发NotifyPropertyChanged。 – SvenG

回答

1

最好的方法是改变你的绑定焦点ListCollectionViews因为这将允许你管理光标下面是一个例子:

视图模型

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Windows.Data; 

    namespace BindingSample 
    { 
     public class ViewModel 
     { 
      private string[] _items = new[] { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }; 

      public ViewModel() 
      { 
       List1 = new ListCollectionView(_items); 
       List2 = new ListCollectionView(_items); 
       List3 = new ListCollectionView(_items); 

       List1.CurrentChanged += (sender, args) => SyncSelections(List1); 
       List2.CurrentChanged += (sender, args) => SyncSelections(List2); 
       List3.CurrentChanged += (sender, args) => SyncSelections(List3); 
      } 

      public ListCollectionView List1 { get; set; } 

      public ListCollectionView List2 { get; set; } 

      public ListCollectionView List3 { get; set; } 

      private void SyncSelections(ListCollectionView activeSelection) 
      { 
       foreach (ListCollectionView view in new[] { List1, List2, List3 }) 
       { 
        if (view != activeSelection && view.CurrentItem == activeSelection.CurrentItem) 
         view.MoveCurrentTo(null); 
       } 
      } 
     } 
    } 

查看

<Window x:Class="ContextMenuSample.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 
    <StackPanel Orientation="Vertical"> 
     <ListBox ItemsSource="{Binding List1}" /> 
     <ListBox ItemsSource="{Binding List2}" /> 
     <ListBox ItemsSource="{Binding List3}" />   
    </StackPanel> 
</Window> 

这将使您只能选择一个项目。目前它是硬编码的,但对于其他列表可以很容易地变得更加灵活。

+0

感谢您的回答,但按照您的方式,我需要在每个对象中使用相同的列表。难道不可以用一个静态列表(所有对象的一个​​列表)来做到这一点? – iop

+0

只有一个实际列表,如_items变量中所定义。 List1,List2和List3只是这个静态数据源的视图。 –