简体   繁体   中英

How to programmatically disable ComboBox items which satisfy condition

In a ComboBox there are some items which have to be enabled and some which have to be disabled (and visible).

At first the ComboBox ItemsSource is set:

comboBoxMachine.ItemsSource = machineList;

where comboBoxMachine is a ComboBox and machineList is a List<Machine> ( Machine is a custom object)

Later a condition for each machine from the list has to be checked and in case it is fulfilled the appropriate item from the ComboBox has to be disabled.

Below is the combination of code/pseudocode of the logic:

private void modifyMachineComboBoxItems()
    {
        foreach (Machine mch in machineList)
        {
            if (constructionSiteSchedule.ReservationMachinePeriods.Count(x => x.MachineId == mch.Id) > 0) //if this condition is fulfilled, it should be not possible to select the machine from the comboBoxMachine
            {
                int currentPosition = machineList.IndexOf(mch);
                disable the element from the comboBoxMachine at position currentPosition;
            }
        }
    }

What I haven't figured out so far is how to disable the element from the ComboBox at given position so I would be very thankful if anyone could modify the code above such that the ComboBox items for machines that satisfy the condition are disabled.

You should just have boolean property on your machine that corresponds to whether the item is enabled, in your ComboBox.ItemContainerStyle you can bind IsEnabled to that property, then when you want to disable the item just set the property on the machine to false.


Alternatively you could use the ItemContainerGenerator (which you really should not):

var item = comboBoxMachine.ItemContainerGenerator.ContainerFromIndex(currentPosition) as ComboBoxItem;
item.IsEnabled = false;

(You do not need to get the position first by the way as there also is a ContainerFromItem method, also see the comment below )

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