Home > OS >  WPF DataBinding: How to bind "IsEnabled" of a ComboBoxItem if the ComboBox "ItemsSour
WPF DataBinding: How to bind "IsEnabled" of a ComboBoxItem if the ComboBox "ItemsSour

Time:04-07

Currently I'm creating a custom Style for a ComboBox.

Current State of Styling

The next step should be the IsEnabled state of the ComboBoxItems. Therefore I created a Simple User Class and a UserList ObservableCollection bound to the ComboBox.

public class User
{
    public int Id { get; private init; }
    public string Name { get; private init; }
    public bool IsEnabled { get; private init; }

    public User(int id, string name, bool isEnabled = true)
    {
        Id = id;
        Name = name;
        IsEnabled = isEnabled;
    }
}
<ComboBox
    ItemsSource="{Binding UserList}"
    DisplayMemberPath="Name"
    SelectedItem="{Binding SelectedUser}"
    IsEnabled="{Binding IsComboboxEnabled}"
    IsEditable="{Binding IsComboboxEditable}"
/>

To create and test the Disabled Style of the ComboBoxItems I want to Bind the IsEnabled Property of the User to the IsEnabled Property of the ComboBoxItem.

But I can't use a ItemContainerStyle here, because this overrides my custom Style:

<ComboBox
   ...
>
    <ComboBox.ItemContainerStyle>
        <Style TargetType="ComboBoxItem">
            <Setter Property="IsEnabled" Value="{Binding IsEnabled}" />
        </Style>
    </ComboBox.ItemContainerStyle>
</ComboBox>

So: How can I bind the IsEnabled Property without using a ItemContainerStyle or destroying the custom style I already add to the ComboBox?

CodePudding user response:

If you have a custom ComboBoxItem Style that you don't want to override, then your Style inside the ItemContainerStyle should have a BasedOn, which will basically copy your default style, then add/replace with whatever is contained:

<Style TargetType="ComboBoxItem" BasedOn="YourComboBoxItemStyle">

Otherwise, if you have a ComboBox Style and want to add this then in either your Style in your ResourceDictionary you can add a Style.Resources in the Style that targets the ComboBoxItem:

<Style TargetType="ComboBox" x:Key="MyComboBoxStyle">
   <Setter .../>
   <Setter .../>
   <Style.Resources>
      <Style TargetType="ComboBoxItem">
         <Setter Property="IsEnabled" Value="{Binding IsEnabled}" />
      </Style>
   </Style.Resources>
</Style>

I hope I understood the question and that my answer is helpful.

  • Related