C#WPF ComboBox - 允许每个列表只选择一次项目

时间:2012-05-22 08:05:03

标签: c# wpf mvvm combobox observablecollection

我使用C#,WPF并尝试使用MVVM。所以我有一个MyObjects的ObservableCollection。该列表呈现为DataGrid,MyObject的一个属性是项的静态列表,显示在每行的ComboBox中。

现在我想在这个组合框中的一行中选择一个项目,如果之前在另一行中选择了它,则必须将最后一个选择移除到默认值。我该怎么办呢?我的MyObjectViewModel知道它自己的“组合框”的变化,但它如何告诉MainViewModel(它包含MyObjects的ObservableCollection)从另一个MyObject对象更改最后选择的ComboBox项?

1 个答案:

答案 0 :(得分: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>

这将允许您只选择一个项目。它现在是硬编码的,但可以更容易地为其他列表更灵活。

相关问题