C# WPF 组合框 - 允许每个列表仅选择一次项

本文关键字:选择 一次 列表 组合 WPF 许每个 | 更新日期: 2023-09-27 18:35:06

我使用C#,WPF并尝试使用MVVM。 所以我有一个 MyObject 的可观察集合。 该列表呈现到 DataGrid 中,MyObject 的一个属性是项的静态列表,显示在每行的组合框中。

现在我想在此组合框中的一行中选择一个项目,如果之前在另一行中选择了它,则必须将最后一个选择删除为默认值。我该如何管理?我的 MyObjectViewModel 知道它"自己的"组合框的更改,但它如何告诉 MainViewModel(其中包含 MyObjects 的 ObservableCollection)从另一个 MyObject 对象更改最后一个选定的 ComboBox 项?

C# WPF 组合框 - 允许每个列表仅选择一次项

执行此操作的最佳

方法是将绑定焦点更改为 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>

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