2009-08-11 15 views
29

Estoy intentando crear un botón que tenga 3 imágenes: una imagen Normal, una Imagen presionada y una Imagen Inhabilitada (las usaré para crear botones de flecha arriba/abajo).WPF - Cómo crear botón de imagen con plantilla

Creo que el enfoque correcto sería derivar de Button y usar un Template y configurar desencadenantes para cambiar la imagen. Tengo 3 propiedades de dependencia, una para cada imagen.

Las imágenes serían .png y tienen fondos transparentes (ya que no son rectangulares).

Estoy buscando algo así como CBitmapButton en MFC.

Respuesta

69

No necesitará propiedades de dependencia porque hereda de Button. Ya tiene las propiedades IsPressed y IsEnabled. De hecho, esto es todo lo que necesita:

<Button x:Class="TestWpfApplication.ThreeStateImageButton" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
    <Button.Template> 
     <ControlTemplate TargetType="{x:Type Button}"> 
     <Grid> 
      <Image Name="Normal" Source="Resources/Normal.png"/> 
      <Image Name="Pressed" Source="Resources/Pressed.png" Visibility="Hidden"/> 
      <Image Name="Disabled" Source="Resources/Disabled.png" Visibility="Hidden"/> 
     </Grid> 
     <ControlTemplate.Triggers> 
      <Trigger Property="IsPressed" Value="True"> 
       <Setter TargetName="Normal" Property="Visibility" Value="Hidden"/> 
       <Setter TargetName="Pressed" Property="Visibility" Value="Visible"/> 
      </Trigger> 
      <Trigger Property="IsEnabled" Value="False"> 
       <Setter TargetName="Normal" Property="Visibility" Value="Hidden"/> 
       <Setter TargetName="Disabled" Property="Visibility" Value="Visible"/> 
      </Trigger> 
     </ControlTemplate.Triggers> 
     </ControlTemplate> 
    </Button.Template> 
</Button> 

Con su UserControl archivo de código subyacente:

public partial class ThreeStateImageButton : Button 
{ 
    public ThreeStateImageButton() 
    { 
     InitializeComponent(); 
    } 
} 
+9

Exactamente. De hecho, heredar de Button es superfluo. Puede hacer todo con esta plantilla y un estilo para aplicarla. La regla aquí debería ser si necesita cambiar el comportamiento, heredar y hacer un control. Si necesita cambiar "Buscar", entonces use un estilo. –

+0

Gracias por su respuesta. Esto es lo que estaba buscando. –

+0

GRACIAS. Esta es la única solución de botón de imagen que funcionó para mí. ¡Incluso he agregado un gatillo "Hover", Major Kudos! – dortzur

1

que he proporcionado una alternativa a esta solución, su peso no es tan ligero, pero que ofrece mucho mayor reutilización.

WPF TriState Image Button

1
public static readonly DependencyProperty DefaultImageSourceProperty = DependencyProperty.Register("DefaultImageSource", typeof(ImageSource), typeof(PressedImageButton), new PropertyMetadata(null, new PropertyChangedCallback(DefaultImageSourceChangedCallback))); 
    public static readonly DependencyProperty PressedImageSourceProperty = DependencyProperty.Register("PressedImageSource", typeof(ImageSource), typeof(PressedImageButton), new PropertyMetadata(null, new PropertyChangedCallback(PressedImageSourceChangedCallback))); 
    public static readonly DependencyProperty ImageStretchProperty = DependencyProperty.Register("ImageStretch", typeof(Stretch), typeof(PressedImageButton), new PropertyMetadata(Stretch.None, new PropertyChangedCallback(ImageStretchChangedCallback))); 

<ControlTemplate> 
     <Grid> 
      <Image Name="imgDefault" Source="{Binding Path=DefaultImageSource,ElementName=uc}" Stretch="{Binding Path=ImageStretch,ElementName=uc}"></Image> 
      <ContentPresenter Content="{TemplateBinding Property=ContentControl.Content}" /> 
     </Grid> 
     <ControlTemplate.Triggers> 
      <Trigger Property="Button.IsPressed" Value="True"> 
       <Setter Property="Image.Source" TargetName="imgDefault" Value="{Binding Path=PressedImageSource,ElementName=uc}"></Setter> 
       <Setter Property="UIElement.Effect"> 
        <Setter.Value> 
         <DropShadowEffect BlurRadius="10" Color="Black" Direction="0" Opacity="0.6" RenderingBias="Performance" ShadowDepth="0" /> 
        </Setter.Value> 
       </Setter> 
      </Trigger> 
      <Trigger Property="Button.IsMouseOver" Value="True"> 
       <Setter Property="UIElement.Effect"> 
        <Setter.Value> 
         <DropShadowEffect BlurRadius="10" Color="White" Direction="0" Opacity="0.6" RenderingBias="Performance" ShadowDepth="0" /> 
        </Setter.Value> 
       </Setter> 
      </Trigger> 
     </ControlTemplate.Triggers> 
    </ControlTemplate> 
-3

La forma más sencilla en WPF:

  1. Crear una imagen de botón con Photoshop u otros programas.

  2. Colóquelo en su ventana y utilice los eventos MouseEnter y MouseLeave.

    private void img1_MouseEnter(object sender, MouseEventArgs e) 
    { 
        Cursor = Cursors.Hand; 
    } 
    
    private void img1_MouseLeave(object sender, MouseEventArgs e) 
    { 
        Cursor = Cursors.Arrow; 
    } 
    
+1

La pregunta indica claramente que necesitan un botón de imagen con una plantilla.Un botón de Photoshop no constituye una plantilla de ningún tipo, además de que no necesita manejar los eventos MouseEnter y MouseLeave para cambiar el cursor, tiene la propiedad Cursor para eso. Una cosa más, no asuma que el cursor normal es una flecha, podría ser otra cosa, puede configurar el Cursor para que vuelva a la normalidad. – Hannish

-1

simplemente tratar este código

<Button Name="btn_Refresh" Grid.Column="0" Height="25" Width="25" HorizontalAlignment="Right" VerticalAlignment="Center" Background="White" Margin="0,0,10,0" Click="btn_Refresh_Click"> 
         <Button.Content> 
          <Grid> 
           <Path Width="15" Height="15" Fill="Blue" Stretch="Fill" Data="F1 M 38,20.5833C 42.9908,20.5833 47.4912,22.6825 50.6667,26.046L 50.6667,17.4167L 55.4166,22.1667L 55.4167,34.8333L 42.75,34.8333L 38,30.0833L 46.8512,30.0833C 44.6768,27.6539 41.517,26.125 38,26.125C 31.9785,26.125 27.0037,30.6068 26.2296,36.4167L 20.6543,36.4167C 21.4543,27.5397 28.9148,20.5833 38,20.5833 Z M 38,49.875C 44.0215,49.875 48.9963,45.3932 49.7703,39.5833L 55.3457,39.5833C 54.5457,48.4603 47.0852,55.4167 38,55.4167C 33.0092,55.4167 28.5088,53.3175 25.3333,49.954L 25.3333,58.5833L 20.5833,53.8333L 20.5833,41.1667L 33.25,41.1667L 38,45.9167L 29.1487,45.9167C 31.3231,48.3461 34.483,49.875 38,49.875 Z " Margin="-8.3,-2,-5.701,0"/> 
          </Grid> 
         </Button.Content> 
        </Button>