简体   繁体   中英

How to bind one ObservableCollection as ItemsSource to different comboBoxes (models) if using wpf ItemsControl with MVVM pattern?

I dynamically create a list of comboBoxes to different Models using wpf ItemsControl element using MVVM pattern. I want to have a logic like if i select an element in one of the comboBoxes, then in all the others it will not appear. I have difficulty with that when i use ItemsControl (ItemsSource - list of my Models) and create elements for it in VievModel - binding is not working, it works only when i have a comboBox items list for each of Models (Model class), not for all comboBoxes (in ViewModel class). Can i have, for example, 1 ObservableCollection for comboBox items in ViewModel and use also ItemsControl to create comboBoxes?

My View :

    <ItemsControl ItemsSource="{Binding Items}" Grid.Row="1">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"  />
                            <ColumnDefinition Width="*"  />
                        </Grid.ColumnDefinitions>
                        <Label  Content="{Binding Name}" Grid.Column="0" />
                        <ComboBox  ItemsSource="{Binding ComboBoxItems}" Grid.Column="1"  
                                   SelectedItem="{Binding SelectedItem}"/>
</Grid>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

ViewModel:

public ObservableCollection<Model> Items { get; set; }

// if I add here public ObservableCollection<string> ComboBoxItems { get; set; } 
// binding isn't working, so I add it to Model class, but in it it does not work as I need.

public ViewModel()
{
Items = new ObservableCollection<Model>();
Items.Add(new Model {Name = "11111"});
Items.Add(new Model {Name = "22222"});
}

Model:

 public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            OnPropertyChanged("Name");
        }
    }
 public string SelectedItem
    {
        get { return _selectedItem; }
        set
        {
            _selectedItem = value;
            OnPropertyChanged("SelectedItem");
        }
    }

public ObservableCollection<string> ComboBoxItems {get;set;}

public Model()
{
ComboBoxItems = new ObservableCollection<string>();
ComboBoxItems.Add("q");
ComboBoxItems.Add("w");
ComboBoxItems.Add("e");
ComboBoxItems.Add("r");
ComboBoxItems.Add("t");
ComboBoxItems.Add("y");
}

1 ObservableCollection for comboBox items in ViewModel and use also ItemsControl to create comboBoxes This means u wanna bind the same ObservableCollection to ur ItemsControl and ComboBox if not please let me know in comment

Ans

   <ItemsControl ItemsSource="{Binding Items}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"  />
                            <ColumnDefinition Width="*"  />
                        </Grid.ColumnDefinitions>
                        <Label  Content="{Binding Name}" Grid.Column="0" />
                        <ComboBox  ItemsSource="{Binding Items ,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ItemsControl}}" Grid.Column="1"  
                                  DisplayMemberPath="Name" SelectedItem="{Binding SelectedItem}"/>
                    </Grid>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

i Binded Items to ComboBox

In order to achieve your goal, you can filter view of ComboBoxItems . You can do it in single source single view way, which you only need to change your ViewModel 's constructor like:

public ViewModel()
{
    Items = new ObservableCollection<Model>();
    Items.Add(new Model {Name = "11111"});
    Items.Add(new Model {Name = "22222"});
    Items.Add(new Model {Name = "33333"});

    foreach (var item in Items)
    {
        CollectionViewSource.GetDefaultView(item.ComboBoxItems).Filter =
            (x) => !Items.Where((y) => y != item).Select(y => y.SelectedItem).Any(y => y == (string)x);

        item.PropertyChanged += (s, e) =>
        {
            foreach (var obj in Items.Where((x) => x != item).Select(x => x.ComboBoxItems))
                CollectionViewSource.GetDefaultView(obj).Refresh();
        };
    }    
}

Or you can also do it in single source multiple view way, which allow you discard your model.

public class ViewModel
{
    private List<string> _comboBoxItems = new List<string> { "q", "w", "e", "r", "t", "y" };
    private List<ICollectionView> _comboBoxViews = new List<ICollectionView>();

    public ObservableCollection<string> Names { get; set; } = new ObservableCollection<string> { "111", "222", "333" };

    public ICollectionView ComboBoxView
    {
        get
        {
            var view = new CollectionViewSource { Source = _comboBoxItems}.View;
            _comboBoxViews.Add(view);
            view.MoveCurrentToPosition(-1);

            view.Filter = (x) => !_comboBoxViews.Where(y => y != view).Any(y => (string)y.CurrentItem == (string)x);

            view.CurrentChanged += (s, e) =>
            {
                foreach (var v in _comboBoxViews.Where(x => x != view))
                    v.Refresh();
            };

            return view;
        }
    }
}

<ItemsControl ItemsSource="{Binding Names}" Grid.Row="1">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"  />
                    <ColumnDefinition Width="*"  />
                </Grid.ColumnDefinitions>
                <Label  Content="{Binding}" Grid.Column="0" />
                <ComboBox  ItemsSource="{Binding DataContext.ComboBoxView, RelativeSource={RelativeSource AncestorType=ItemsControl}}"
                           Grid.Column="1"/>
            </Grid>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM