覆盖ComboBox样式?

时间:2017-03-04 11:39:15

标签: c# wpf xaml combobox

Style中的Window.Resources已应用于应用中的所有ComboBox。但是,我遇到的情况是我需要Window.Resources中应用于ComboBox的样式,但我需要禁用我在样式中专门设置的一个功能。

我希望能够在应用程序中的一个ComboBox中输入文本。 由于ComboBox文本可编辑部分实际上是TextBox我设置完全禁用了TextBox:此样式专门针对我拥有的ComboBox样式,

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

我还将ComboBox个样式IsEditable设置为false。我必须将此样式应用于TextBox ComboBox部分的样式才能正常工作。我还将指向静态资源的代码包含在上面显示的x:Key="ComboBoxTextBoxStyle"中:

<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  

所以现在我有一个ComboBox我希望能够输入文本,所以我将XAML设置为此,

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

但即使我已将ComboBox设置为ComboBoxIsEditable="True"也无法输入文字。

如何覆盖样式以允许此ComboBox输入文本?

1 个答案:

答案 0 :(得分:1)

你必须创建一个新的Style,它将继承已存在的Style并将其应用于该特定的combox框,样式如下:

更好的方法是,ComboBox IsEnabled属性的样式模板中的TextBox元素应该绑定到ComboBox IsEditable属性:

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

然后在xaml消费方面你可以指定这种风格:

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