Thursday, October 10, 2019

Setting a combo box item disabled

I had a colleague ask me how to set a combo box item disabled and while I knew it could be done, I couldn't remember the details immediately. So I'm writing this blog entry so I never have to think about it again.

Start a new C# WPF project, any framework. Call the project DisableComboBoxItem.

Here's the MainWindow's XAML - the style enforces the disabling of the items.


<Window x:Class="DisableComboBoxItem.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:DisableComboBoxItem"
        DataContext="{Binding RelativeSource={RelativeSource Self}}"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <Style TargetType="ComboBoxItem">
            <Setter Property="IsEnabled" Value="{Binding IsEnabled}"/>
        </Style>
    </Window.Resources>
    <ComboBox Width="100" Height="20" ItemsSource="{Binding Items}" DisplayMemberPath="Name" IsEditable="False"/>
</Window>

Here's the code behind. Its only job is to initialize the items source.


using System.Collections.Generic;
using System.Windows;

namespace DisableComboBoxItem
{

    public class cItem
    {
        public string Name { get; set; }
        public bool IsEnabled { get; set; }
    }

    public partial class MainWindow : Window
    {
        private List<cItem> _Items = new List<cItem>()
            {
                new cItem() {Name="Enabled", IsEnabled=true},
                new cItem() {Name="Disabled", IsEnabled=false}
            };

        public List<cItem> Items { get { return _Items; } }

        public MainWindow()
        {
            InitializeComponent();
        }
    }
}

Here's the result. Pretty impressive eh? LOL


No comments:

Post a Comment