KyloRen
KyloRen

Reputation: 2741

Override ComboBox Styles?

I have a Style in Window.Resources applied to all the ComboBox in the application. However, I have come across a situation where I need the styles in the Window.Resources applied to the ComboBox, but I need to disable one feature I have specifically set in the styles.

I want to be able to enter text into one ComboBox in the application. Being that the ComboBox text editable part is actually a TextBox I set disabled the TextBox altogether: This style is specifically for the ComboBox style I have,

<Style x:Key="ComboBoxTextBoxStyle" TargetType="{x:Type TextBox}">
            <Setter Property="IsEnabled" Value="False" />
            <....More setters etc

I have also set in the ComboBox styles IsEditable to false. I had to apply this style to both the TextBox part of the ComboBox to the style work correctly. I have also included the code pointing to the static resource to x:Key="ComboBoxTextBoxStyle" shown above:

<Style TargetType="{x:Type ComboBox}">
            <Setter Property="IsEditable" Value="False" />
            <...More setter's
               <Setter.Value>
                   <ControlTemplate TargetType="{x:Type ComboBox}">
                        <TextBox Style="{StaticResource ComboBoxTextBoxStyle}" 
                         <...More styles applied here  

So now I have a ComboBox that I want to be able to enter text into, so I set the XAML to this,

<ComboBox x:Name="Cmb" IsEditable="True" 
  ItemsSource="{Binding Source={x:Static viewModels:ShiftManagerViewModel.MyBindingList}}"
  SelectedItem="{Binding UpdateSourceTrigger=PropertyChanged, Path=MySeletcProperty}" />

But, the ComboBox is not able to be able to enter text even though I have set the actuall ComboBox to IsEditable="True".

How do I override the styles to allow this one ComboBox enter text?

Upvotes: 1

Views: 659

Answers (1)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

You would have to create a new Style which will inherit from that Style that already exists and apply it to that particular combox box, style would be like:

A better apporach is that your TextBox element in Style Template for ComboBox IsEnabled property should have binding to ComboBox IsEditable property :

<Style x:Key="ComboBoxTextBoxStyle" TargetType="{x:Type TextBox}">
  <Setter Property="IsEnabled" 
          Value="{Binding Path=IsEditable, RelativeSource={RelativeSource AncestorType={x:Type ComboBox}}}" />

and then in xaml consuming side you can specify this style :

<ComboBox x:Name="Cmb" IsEditable="True"
  ItemsSource="{Binding Source={x:Static viewModels:ShiftManagerViewModel.MyBindingList}}"
  SelectedItem="{Binding UpdateSourceTrigger=PropertyChanged, Path=MySeletcProperty}" />

Upvotes: 1

Related Questions