This article is currently in the process of being translated into Russian (~19% done).

Основные элементы управления:

The Button control

Ни один фреймворк для GUI не будет закончен без кнопок, поэтому, конечно, и WPF их имеет. И, как остальные элементы фреймворка, они очень гибкие и позволяют сделать почти все, но давайте начнем с более простых примеров.

A simple Button

Так же, как и многие другие элементы управления WPF, кнопку можно добавить, вписав тэг Button в ваше окно. Если вы напишите текст (или вставите другой элемент), он станет содержимым кнопки:

<Button>Hello, world!</Button>

Довольно просто, да? Конечно, кнопка пока ничего не делает, но если вы наведете на нее мышью, вы увидите, что у нее уже есть хороший встроенный эффект. Но давайте все-таки заставим кнопку что-нибудь сделать, "подписавшись" на событие Click (больше информации про события в статье "события в XAML"):

<Button Click="HelloWorldButton_Click">Hello, World!</Button>

В коде на C# вам нужен метод с таким именем, чтобы обработать событие по нажатии на кнопку:

private void HelloWorldButton_Click(object sender, RoutedEventArgs e)
    MessageBox.Show("Hello, world!");

Теперь у вас есть очень простая кнопка и когда вы нажмете на нее, вы увидите сообщение!

Formatted content

Internally, simple text inside the Content of the Button is turned into a TextBlock control, which also means that you can control the same aspects of the text formatting. You will find several properties on the Button control for doing this, including (but not limited to) Foreground, Background, FontWeight and so on. In other words, it's very easy to change the formatting of the text inside a Button control:

<Button Background="Beige" Foreground="Blue" FontWeight="Bold">Formatted Button</Button>

By setting these properties directly on the Button, you are of course limited to applying the same formatting for all of the content, but if that's not good enough, just read on for even more advanced content formatting.

Buttons with advanced content

We have already talked about this several times, but one of the very cool things about WPF is the ability to replace simple text inside a control with other WPF controls. This also means that you don't have to limit your buttons to simple text, formatted in the same way - you can just add several text controls with different formatting. The WPF Button only supports one direct child control, but you can just make that a Panel, which will then host as many controls as you need to. You can use this to create buttons with various types of formatting:

    <StackPanel Orientation="Horizontal">
<TextBlock>Formatted </TextBlock>
<TextBlock Foreground="Blue" FontWeight="Bold" Margin="2,0">Button</TextBlock>
<TextBlock Foreground="Gray" FontStyle="Italic">[Various]</TextBlock>

But of course, you are not limited to just text - you can put whatever you want inside your buttons, which leads us to a subject that I know many people will ask for. Buttons with images!

Buttons with Images (ImageButton)

In many UI frameworks, you will find a regular Button and then one or several other variants, which will offer extra features. One of the most commonly used variants is the ImageButton, which, as the name implies, is a Button which will usually allow you to include an image before the text. But in WPF, there's no need for a separate control to accomplish this - as you just saw, we can put several controls inside a Button, so you can just as easily add an Image control to it, like this:

<Button Padding="5">  
    <StackPanel Orientation="Horizontal">  
<Image Source="/WpfTutorialSamples;component/Images/help.png" />  
<TextBlock Margin="5,0">Help</TextBlock>  

It's really that simple to create an ImageButton in WPF, and you are of course free to move things around, e.g. if you want the image after the text instead of before etc.

Button Padding

You may have noticed that buttons in the WPF framework doesn't come with any padding by default. This means that the text is very close to the borders, which might look a little bit strange, because most buttons found elsewhere (web, other applications etc.) do have at least some padding in the sides. No worries, because the Button comes with a Padding property:

<Button Padding="5,2">Hello, World!</Button>

This will apply a padding of 5 pixels on the sides, and 2 pixels in the top and bottom. But having to apply padding to all of your buttons might get a bit tiresome at a certain point, so here's a small tip: You can apply the padding globally, either across the entire application or just this specific Window, using a Style (more on styles later). Here's an example where we apply it to the Window, using the Window.Resources property:

    <Style TargetType="{x:Type Button}">
<Setter Property="Padding" Value="5,2"/>

This padding will now be applied to all your buttons, but you can of course override it by specifically defining the Padding property on a Button. Here's how all the buttons of this example look with the common padding:


As you can see from this article, using buttons in the WPF framework is very easy and you can customize this important control almost endlessly.

This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!