WPF ComboBox style
时间: 2023-10-14 21:25:19 浏览: 80
以下是一个简单的 WPF ComboBox 样式示例:
```xml
<Window.Resources>
<Style x:Key="ComboBoxStyle" TargetType="{x:Type ComboBox}">
<Setter Property="Foreground" Value="Black"/>
<Setter Property="Background" Value="White"/>
<Setter Property="FontSize" Value="14"/>
<Setter Property="Padding" Value="5,2"/>
<Setter Property="Height" Value="30"/>
<Setter Property="Width" Value="120"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ComboBox}">
<Grid>
<ToggleButton x:Name="ToggleButton" BorderBrush="Gray" BorderThickness="1" Background="{TemplateBinding Background}" Foreground="{TemplateBinding Foreground}" Grid.Column="2" Focusable="false" IsChecked="{Binding Path=IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}" >
<ToggleButton.Template>
<ControlTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition Width="20" />
</Grid.ColumnDefinitions>
<Border x:Name="Border" Background="{TemplateBinding Background}" BorderThickness="0" CornerRadius="0" Grid.ColumnSpan="2" />
<Path x:Name="Arrow" Grid.Column="1" Fill="{TemplateBinding Foreground}" HorizontalAlignment="Center" VerticalAlignment="Center" Data="M 0 0 L 4 4 L 8 0 Z"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="Border" Property="Background" Value="#EEE" />
<Setter TargetName="Border" Property="BorderBrush" Value="#AAA" />
<Setter Property="Foreground" Value="#AAA"/>
<Setter TargetName="Arrow" Property="Fill" Value="#AAA" />
</Trigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="Border" Property="Background" Value="#DDD" />
</Trigger>
<Trigger Property="IsChecked" Value="True">
<Setter TargetName="Border" Property="Background" Value="#EEE" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</ToggleButton.Template>
</ToggleButton>
<Popup x:Name="Popup" Placement="Bottom" IsOpen="{TemplateBinding IsDropDownOpen}" AllowsTransparency="True" Focusable="False" PopupAnimation="Slide">
<Grid x:Name="DropDown" SnapsToDevicePixels="True" MinWidth="{TemplateBinding ActualWidth}" MaxHeight="{TemplateBinding MaxDropDownHeight}">
<Border x:Name="DropDownBorder" Background="White" BorderThickness="1" BorderBrush="Gray"/>
<ScrollViewer Margin="4,6,4,6" SnapsToDevicePixels="True">
<ItemsPresenter SnapsToDevicePixels="True" />
</ScrollViewer>
</Grid>
<Popup.Style>
<Style TargetType="{x:Type Popup}">
<Style.Triggers>
<Trigger Property="HasDropShadow" Value="True">
<Setter Property="Margin" Value="0,0,5,5" />
</Trigger>
</Style.Triggers>
</Style>
</Popup.Style>
</Popup>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<StackPanel>
<ComboBox Style="{StaticResource ComboBoxStyle}" ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}" />
</StackPanel>
```
这个样式将 ComboBox 的默认外观替换为一个带有箭头的按钮,单击该按钮将显示一个下拉列表。你可以使用这个样式作为起点,自定义一些属性来满足你的需求。
阅读全文