WPF自定义控件不使用切换按钮的默认样式

本文关键字:按钮 默认 样式 自定义控件 WPF | 更新日期: 2023-09-27 18:12:00

我正在创建一个基于ToggleButton的自定义控件。在Generic中使用这个简单的样式。我不能让默认的切换按钮样式在我的自定义控件上工作。

我将前景,背景和borderbrush设置为systemcolors,但是没有任何变化。

  <Style TargetType="{x:Type local:PopupButton}" BasedOn="{StaticResource {x:Type ToggleButton}}">
    <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
    <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}" />
    <Setter Property="BorderBrush" Value="{DynamicResource {x:Static SystemColors.ActiveBorderBrushKey}}" />
    <Setter Property="HorizontalAlignment" Value="Center" />
    <Setter Property="VerticalAlignment" Value="Center" />
    <Setter Property="MinHeight" Value="22" />
    <Setter Property="MinWidth" Value="75" />
    <Setter Property="Template">
      <Setter.Value>
        <ControlTemplate TargetType="{x:Type local:PopupButton}">
          <Grid SnapsToDevicePixels="True">
            <Grid.ColumnDefinitions>
              <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
            <ToggleButton Grid.Column="0">
              <ToggleButton.Template>
                <ControlTemplate TargetType="{x:Type ToggleButton}">
                  <ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" 
                                    HorizontalAlignment="Stretch" VerticalAlignment="Stretch" 
                                    RecognizesAccessKey="True" />
                </ControlTemplate>
              </ToggleButton.Template>
              <ContentPresenter Content="{TemplateBinding Content}"
                                ContentTemplate="{TemplateBinding ContentTemplate}"
                                VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                                HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                Margin="{TemplateBinding Margin}"
                                RecognizesAccessKey="true" />
            </ToggleButton>
          </Grid>
        </ControlTemplate>
      </Setter.Value>
    </Setter>
  </Style>
我已经重写了defaultstylekey:
public class PopupButton : ToggleButton
  {
    static PopupButton()
    {
      DefaultStyleKeyProperty.OverrideMetadata(typeof(PopupButton), new FrameworkPropertyMetadata(typeof(PopupButton)));
    }
// ...

一直在测试,玩周围的其他(xaml)代码,但几个小时后,我仍然没有弄清楚为什么默认的样式不应用

WPF自定义控件不使用切换按钮的默认样式

在你的ControlTemplate for local:PopupButton中,你有一个切换按钮,但是你也覆盖了它的模板。试着删除:

<ToggleButton.Template>
    <ControlTemplate TargetType="{x:Type ToggleButton}">
        <ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" 
                                HorizontalAlignment="Stretch" VerticalAlignment="Stretch" 
                                RecognizesAccessKey="True" />
    </ControlTemplate>
</ToggleButton.Template>