WPF, style for buttons in XAML


I'm a C # programmer and I'm just using WPF and I'd like to replicate these buttons in xaml, starting with their form!

asked by Nelson Bueno 04.05.2016 в 04:22

1 answer


Basically these controls are created with styles (Styles) and attached properties (Attached Properties), sometimes you can also use triggers (Triggers) with the XAML language.

For example, you can create a button in the following way, using a resource file or in the same XAML of your page:

    <Style x:Key="Imagen1" TargetType="Button">
        <Setter Property="ContentTemplate">
                    <StackPanel Orientation="Horizontal">
                        <Image Source="{Binding Path=(botoncito:ButtonProperties.Image), RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}}"></Image>
                        <ContentPresenter Content="{Binding Path=Content, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}}"></ContentPresenter>

We define the attached properties (Attached Properties) by means of code C #:

public class PropiedadesBoton
    public static ImageSource GetImage(DependencyObject obj)
        return (ImageSource)obj.GetValue(ImageProperty);

    public static void SetImage(DependencyObject obj, ImageSource value)
        obj.SetValue(ImageProperty, value);

    public static readonly DependencyProperty ImageProperty =
        DependencyProperty.RegisterAttached("Image", typeof(ImageSource), typeof(PropiedadesBoton), new UIPropertyMetadata((ImageSource)null));

Finally, in your XAML file, where you will use the button itself, you can place the following code:

<Button Style="{StaticResource Imagen1}" botoncito:ButtonProperties.Image="{StaticResource MyImage}" Content="Test">

The tutorial provided by MSDN is quite interesting and complete to learn how to perform this task. Almost all WPF controls can be customized.

answered by 04.05.2016 в 15:10