ComboBox樣式:html
<Window.Resources> <ControlTemplate x:Key="ComboBoxTextBox" TargetType="{x:Type TextBox}"> <Border x:Name="PART_ContentHost" Focusable="False" Background="{TemplateBinding Background}" /> </ControlTemplate> <ControlTemplate x:Key="ComboBoxToggleButton" TargetType="{x:Type ToggleButton}"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition Width="40" /> </Grid.ColumnDefinitions> <Border Grid.Column="0" BorderThickness="2" BorderBrush="#e8e8e8" /> <Border Grid.Column="1" Background="#e8e8e8" Cursor="Hand"/> <Path x:Name="Arrow" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center" Data="M 0 0 L 4 4 L 8 0 Z" Margin="16,16,10,10" Stretch="Fill" Fill="White" /> </Grid> </ControlTemplate> <Style TargetType="{x:Type ComboBox}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ComboBox}"> <Grid> <!-- ToggleButton 已數據綁定到 ComboBox 自己以切換 IsDropDownOpen --> <ToggleButton Grid.Column="2" Template="{DynamicResource ComboBoxToggleButton}" x:Name="ToggleButton" Focusable="false" IsChecked="{Binding Path=IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}" ClickMode="Press"/> <ContentPresenter HorizontalAlignment="Left" Margin="3,3,23,3" x:Name="ContentSite" VerticalAlignment="Center" Content="{TemplateBinding SelectionBoxItem}" ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}" ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}" IsHitTestVisible="False"/> <!-- 必須將 TextBox 命名爲 PART_EditableTextBox,不然 ComboBox 將沒法識別它 --> <TextBox Visibility="Hidden" Template="{DynamicResource ComboBoxTextBox}" HorizontalAlignment="Left" Margin="3,3,23,3" x:Name="PART_EditableTextBox" Style="{x:Null}" VerticalAlignment="Center" Focusable="True" Background="Transparent" IsReadOnly="{TemplateBinding IsReadOnly}"/> <!-- Popup 可顯示 ComboBox 中的項列表。IsOpen 已數據綁定到經過 ComboBoxToggleButton 來切換的 IsDropDownOpen --> <Popup IsOpen="{TemplateBinding IsDropDownOpen}" Placement="Bottom" x:Name="Popup" Focusable="False" AllowsTransparency="True" PopupAnimation="Slide"> <Grid MaxHeight="{TemplateBinding MaxDropDownHeight}" MinWidth="{TemplateBinding ActualWidth}" x:Name="DropDown" SnapsToDevicePixels="True"> <Border x:Name="DropDownBorder" Background="{DynamicResource WindowBackgroundBrush}" BorderBrush="{DynamicResource SolidBorderBrush}" BorderThickness="1"/> <ScrollViewer Margin="4,6,4,6" Style="{DynamicResource SimpleScrollViewer}" SnapsToDevicePixels="True" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" CanContentScroll="True"> <!-- StackPanel 用於顯示子級,方法是將 IsItemsHost 設置爲 True --> <StackPanel IsItemsHost="True" KeyboardNavigation.DirectionalNavigation="Contained" Background="White"/> </ScrollViewer> </Grid> </Popup> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> </Window.Resources>
版權聲明:本文爲博主原創文章,未經博主容許不得轉載。ide