Disallow/Block selection of disabled combobox item in wpf

后端 未结 2 437
情深已故
情深已故 2020-11-30 10:01

I\'m writing an application wherein I would like to disable few items in the ComboBox and also want to disallow/block selection of disabled items. Please note C

相关标签:
2条回答
  • 2020-11-30 10:21

    You can achieve this by setting IsEnabled property of a ComboBoxItem to false;

    So each item in ComboBox's ItemSource (i.e. Cars in your case) can be an object having some property (say IsSelectable) specifying whether it should be enabled or disabled and then use it with a style to make an item un-selectable. something like this -

    <Style TargetType="ComboBoxItem"> 
       <Setter Property="IsEnabled" Value="{Binding IsSelectable}"/> 
    </Style> 
    

    Update:

    <Grid>
        <ComboBox
            Width="120"
            Margin="87.2,44.8,0,0"
            HorizontalAlignment="Left"
            VerticalAlignment="Top"
            ItemTemplateSelector="{StaticResource QualityComboBoxTemplateSelector}"
            ItemsPanel="{DynamicResource ItemsPanelTemplateHorizontal}"
            ItemsSource="{Binding Cars}"
            SelectedItem="{Binding SelectedItm}">
            <ComboBox.ItemContainerStyle>
                <Style TargetType="ComboBoxItem">
                    <Setter
                        Property="IsEnabled"
                        Value="{Binding IsSelectable}" />
                </Style>
            </ComboBox.ItemContainerStyle>
        </ComboBox>
    </Grid>
    
    0 讨论(0)
  • 2020-11-30 10:27

    To solve the problem pointed by @JordyBoom.

    ItemsContainerGenerator does not generate items until dropdown is opened at least once.

    So if you open the drop down and close it again in window’s loaded event handler then all supposed to work fine with mouse as well as with keyboard selection.

        public MainWindow()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(onLoaded);
        }
    
        private void onLoaded(object sender, RoutedEventArgs e)
        {
             cmbx.IsDropDownOpen = true;
             cmbx.IsDropDownOpen = false;
        }
    

    source: WPF: Making combo box items disabled – also when accessed using the keyboard

    0 讨论(0)
提交回复
热议问题