<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 Width="{Binding XPath=bord}"/> </Grid.ColumnDefinitions> <Border x:Name="bord" Grid.Column="0" BorderThickness="2" BorderBrush="#e8e8e8" CornerRadius="5,5,5,5"/> <Border Grid.Column="1" Background="#e8e8e8" Cursor="Hand" CornerRadius="5,5,5,5"/> <Path x:Name="Arrow" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center" Data="M 0 0 L 4 4 L 8 0 Z" Stretch="Fill" Fill="#e8e8e8"/> </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="5,0,0,0" 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" x:Name="PART_EditableTextBox" Style="{x:Null}" VerticalAlignment="Center" Focusable="True" Background="Transparent" Foreground="#2259AA" 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 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>
