WPF, style for buttons in XAML

1

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
source

1 answer

3

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:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:botoncito="clr-namespace:MiProyecto.PropiedadesBoton">
    ...
    <Style x:Key="Imagen1" TargetType="Button">
        <Setter Property="ContentTemplate">
            <Setter.Value>
                <DataTemplate>
                    <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>
                    </StackPanel>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

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">
</Button>

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