C # WPF ComboBox с закругленными углами IsMouseOver не будет работать - PullRequest
0 голосов
/ 31 мая 2018

Я нашел этот код при выполнении закругленных углов в выпадающем списке, я немного изменил его, но у меня есть две проблемы:

1) Перемещение мыши в выпадающем списке (текстовое поле + кнопка переключения) не будет работать.(Мне нужно стандартное поведение с синим фоном при наведении курсора, поместите красный только для того, чтобы увидеть, произошло ли что-то)

2), когда я нажимаю на кнопку переключения, я получаю всплывающее окно, но как сделать текстовое поле активным для щелчка, чтобы получитьвсплывающее окно?

Вот что я получаю:

enter image description here

enter image description here

Это то, что я хочу при наведении курсора мыши (но с закругленным углом)

enter image description here

Вот код:

<Style x:Key="BorderStyle">
    <Setter Property="Control.BorderBrush" Value="#A0A1A2" />
    <Setter Property="Control.BorderThickness" Value="1" />
    <Setter Property="Control.Background" Value="Transparent" />
    <Setter Property="Control.Foreground" Value="#101010" />
    <Setter Property="Control.FontFamily" Value="Arial" />
    <Setter Property="Control.FontWeight" Value="Normal" />
    <Setter Property="Control.FontStretch" Value="Normal" />
    <Setter Property="Control.FontStyle" Value="Normal" />
</Style>

<Style x:Key="ComboBoxTextBoxStyle" TargetType="{x:Type TextBox}">
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="true">
            <Setter Property="Background" Value="Red" />
        </Trigger>
    </Style.Triggers>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type TextBox}">
                <Grid>
                    <Border CornerRadius="2,0,0,2"
                            BorderThickness="1,1,0,1"
                            Background="{TemplateBinding Background}"
                            BorderBrush="#A0A1A2">
                        <ScrollViewer x:Name="PART_ContentHost"/>
                    </Border>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

<Style x:Key="ComboBoxButtonStyle" TargetType="{x:Type ToggleButton}">
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="true">
            <Setter Property="Background" Value="Red" />
        </Trigger>
    </Style.Triggers>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ToggleButton}">
                <Border Background="#EAEAEA" 
                        x:Name="border" 
                        CornerRadius="0,2,2,0" 
                        BorderThickness="0,1,1,1"
                        BorderBrush="#A0A1A2">
                    <ContentPresenter />
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

<Style  x:Key="RoundComboBox" TargetType="{x:Type ComboBox}" BasedOn="{StaticResource BorderStyle}">
    <Setter Property="HorizontalContentAlignment" Value="Left"/>
    <Setter Property="VerticalContentAlignment" Value="Center"/>
    <Setter Property="FontSize" Value="14px"/>
    <Setter Property="IsReadOnly" Value="True"/>
    <Setter Property="Height" Value="25"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ComboBox}">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition/>
                        <ColumnDefinition MaxWidth="18"/>
                    </Grid.ColumnDefinitions>

                    <TextBox Name="PART_EditableTextBox"
                             Padding="0,0,0,0"
                             IsHitTestVisible="False"
                             Height="{TemplateBinding Height}"
                             BorderBrush="#A0A1A2"
                             Background="#EAEAEA"
                             Style="{StaticResource ComboBoxTextBoxStyle}"/>

                    <ToggleButton Grid.Column="1" 
                                  Height="{TemplateBinding Height}"
                                  Style="{StaticResource ComboBoxButtonStyle}"
                                  Focusable="False"
                                  IsChecked="{Binding Path=IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
                                  ClickMode="Press">
                        <Path Grid.Column="1"
                              HorizontalAlignment="Center"
                              VerticalAlignment="Center"
                              Data="M 0 0 L 4 4 L 8 0 Z"
                              Fill="Black" />
                    </ToggleButton>

                    <ContentPresenter Grid.Column="0" 
                                      Name="ContentSite"
                                      Content="{TemplateBinding SelectionBoxItem}"
                                      ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}"
                                      ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}"
                                      VerticalAlignment="Center"
                                      HorizontalAlignment="Left"
                                      Margin="6,0,0,0"/>

                    <Popup Grid.Column="0" 
                           Name="Popup"
                           Placement="Bottom"
                           IsOpen="{TemplateBinding IsDropDownOpen}"
                           AllowsTransparency="True" 
                           Focusable="False"
                           PopupAnimation="Slide">

                        <Grid Name="DropDown"
                              SnapsToDevicePixels="True"                
                              MinWidth="{TemplateBinding ActualWidth}"
                              MaxHeight="{TemplateBinding MaxDropDownHeight}">

                            <Border x:Name="DropDownBorder"
                                    BorderThickness="1"
                                    CornerRadius="2"
                                    Background="White"
                                    BorderBrush="#A0A1A2"/>
                            <ScrollViewer SnapsToDevicePixels="True">
                                <StackPanel IsItemsHost="True" KeyboardNavigation.DirectionalNavigation="Contained" />
                            </ScrollViewer>
                        </Grid>

                    </Popup>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

1 Ответ

0 голосов
/ 31 мая 2018

Здесь было несколько проблем.Каждый элемент, который я изменил в XAML, комментируется.

Я также удалил триггеры IsMouseOver из стилей переключателей и текстовых полей и перевел их в стиль ComboBox.Теперь он устанавливает фон для всего поля со списком, когда мышь находится над ComboBox.Два элемента управления в шаблоне ComboBox теперь имеют Background="{TemplateBinding Background}", поэтому они будут использовать цвет фона, установленный этим триггером.

Я восстановил IsHitTestVisible в текстовом поле, но использовал TemplateBinding, чтобы связать его со свойством IsEditable ComboBox.Это даст вам правильный указатель мыши над текстовым полем.

<!-- 
Better to define this in one place. 
I'd do the same with the border color that you use everywhere. 
-->
<SolidColorBrush x:Key="ComboBackgroundBrush" Color="#EAEAEA" />

<Style x:Key="ComboBoxTextBoxStyle" TargetType="{x:Type TextBox}">
    <!-- 
    Must set this in a setter, not an an attribute on the control instance.
    The attribute you had will override anything the style does. This is part of 
    "dependency property value precedence". 
    -->
    <Setter Property="Background" Value="{StaticResource ComboBackgroundBrush}" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type TextBox}">
                <Grid>
                    <Border CornerRadius="2,0,0,2"
                            BorderThickness="1,1,0,1"
                            Background="{TemplateBinding Background}"
                            BorderBrush="#A0A1A2"
                            >
                        <ScrollViewer x:Name="PART_ContentHost"/>
                    </Border>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

<Style x:Key="ComboBoxButtonStyle" TargetType="{x:Type ToggleButton}">
    <Setter Property="Background" Value="{StaticResource ComboBackgroundBrush}" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ToggleButton}">
                <!-- 
                Needs {TemplateBinding Background} so it uses whatever background brush 
                the control has at any given moment.
                -->
                <Border Background="{TemplateBinding Background}" 
                        x:Name="border" 
                        CornerRadius="0,2,2,0" 
                        BorderThickness="0,1,1,1"
                        BorderBrush="#A0A1A2">
                    <ContentPresenter />
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

<Style x:Key="ComboBoxOverlayToggleButtonStyle" TargetType="ToggleButton">
    <Setter Property="Focusable" Value="False" />
    <Setter Property="ClickMode" Value="Press" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ToggleButton">
                <Grid Background="Transparent" />
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
<Style x:Key="RoundComboBox" TargetType="{x:Type ComboBox}" BasedOn="{StaticResource BorderStyle}">
    <Setter Property="HorizontalContentAlignment" Value="Left"/>
    <Setter Property="VerticalContentAlignment" Value="Center"/>
    <Setter Property="FontSize" Value="14px"/>
    <Setter Property="IsReadOnly" Value="True"/>
    <Setter Property="Height" Value="25"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ComboBox}">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition/>
                        <ColumnDefinition MaxWidth="18"/>
                    </Grid.ColumnDefinitions>

                    <ToggleButton
                        Grid.Column="0"
                        Style="{StaticResource ComboBoxOverlayToggleButtonStyle}"
                        IsChecked="{Binding Path=IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
                        />

                    <!--
                    Two problems: 
                        1. IsHitTestVisible="False" prevented it from getting any mouse messages.
                        2. Background attribute was overriding anything the Style did,
                           so even if the trigger had fired, its setter would have failed. 
                    Also, Height="{TemplateBinding Height}" is unnecessary. It'll size to its parent Grid.
                    And BorderBrush="#A0A1A2" should probably be in the Style
                    -->
                    <TextBox Name="PART_EditableTextBox"
                             Padding="0,0,0,0"
                             BorderBrush="#A0A1A2"
                             Style="{StaticResource ComboBoxTextBoxStyle}"
                             Background="{TemplateBinding Background}"
                             IsHitTestVisible="{TemplateBinding IsEditable}"
                             />

                    <ToggleButton Grid.Column="1" 
                                  Height="{TemplateBinding Height}"
                                  Style="{StaticResource ComboBoxButtonStyle}"
                                  Focusable="False"
                                  IsChecked="{Binding Path=IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
                                  ClickMode="Press"
                                  Background="{TemplateBinding Background}"
                                  >
                        <Path Grid.Column="1"
                              HorizontalAlignment="Center"
                              VerticalAlignment="Center"
                              Data="M 0 0 L 4 4 L 8 0 Z"
                              Fill="Black" />
                    </ToggleButton>

                    <ContentPresenter Grid.Column="0" 
                                      Name="ContentSite"
                                      Content="{TemplateBinding SelectionBoxItem}"
                                      ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}"
                                      ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}"
                                      VerticalAlignment="Center"
                                      HorizontalAlignment="Left"
                                      Margin="6,0,0,0"
                                      />

                    <Popup Grid.Column="0" 
                           Name="Popup"
                           Placement="Bottom"
                           IsOpen="{TemplateBinding IsDropDownOpen}"
                           AllowsTransparency="True" 
                           Focusable="False"
                           PopupAnimation="Slide">

                        <Grid Name="DropDown"
                              SnapsToDevicePixels="True"                
                              MinWidth="{TemplateBinding ActualWidth}"
                              MaxHeight="{TemplateBinding MaxDropDownHeight}">

                            <Border x:Name="DropDownBorder"
                                    BorderThickness="1"
                                    CornerRadius="2"
                                    Background="White"
                                    BorderBrush="#A0A1A2"/>
                            <ScrollViewer SnapsToDevicePixels="True">
                                <StackPanel IsItemsHost="True" KeyboardNavigation.DirectionalNavigation="Contained" />
                            </ScrollViewer>
                        </Grid>

                    </Popup>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="true">
            <Setter Property="Background" Value="Red" />
        </Trigger>
    </Style.Triggers>
</Style>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...