应用基本自定义样式时隐藏的按钮 - WPF

问题描述:

我试图让按钮可视化的PNG(无边框,渐变,无论)。应用基本自定义样式时隐藏的按钮 - WPF

我所做的是:

  • 资源

    <Style x:Key="PlainImageButton" TargetType="{x:Type Button}"> 
        <Setter Property="Template"> 
         <Setter.Value> 
          <ControlTemplate TargetType="Button"> 
           <ContentPresenter HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/> 
          </ControlTemplate> 
         </Setter.Value> 
        </Setter> 
    </Style> 
    
  • XAML

    <Button Width="16" Height="16" Style="{DynamicResource PlainImageButton}"> 
           <Button.Background> 
            <ImageBrush ImageSource="Images/pencil.png"/> 
           </Button.Background> 
         </Button> 
    

但按钮是不可见的

enter image description here

为什么会发生这种情况?

你必须在你的模板中使用提供的背景,例如像这样:

<Button.Template> 
    <ControlTemplate TargetType="{x:Type ButtonBase}"> 
     <Border x:Name="border" Background="{TemplateBinding Background}" SnapsToDevicePixels="True"> 
      <ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" /> 
     </Border> 
    </ControlTemplate> 
</Button.Template> 

您正在提供图像作为按钮中的背景。而在您的模板,你还没有使用的background属性与ContentPresenter结合

试试这个

<Button Width="16" 
       Height="16" 
       Style="{DynamicResource PlainImageButton}"> 
      <Button.Content> 
       <Image Source="pencil.png" /> 
      </Button.Content> 
     </Button> 

在这里,我已经设置了内容为将与ContentPresenter在您的模板被绑定图像

希望它有帮助:)