3

I use C#, WPF and try to use MVVM. So I have an ObservableCollection of MyObjects. The list is rendered into a DataGrid, and one property of MyObject is a static list of items which is shown in a ComboBoxes in each row.

Now I would like to select an item in one row in this combobox, and if it was selected in another row before, the last selection has to be removed to the default value. How can I manage this? My MyObjectViewModel knows about the change of its 'own" combobox but how can it tell the MainViewModel (which holds the ObservableCollection of MyObjects) to change the last selected ComboBox item from another MyObject object?

4

1 回答 1

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>

这将允许您只选择一项。它现在是硬编码的,但可以很容易地使其更灵活地用于附加列表。

于 2012-05-23T11:02:01.563 回答