Demonstra Passo a passo: Create a Button by Using Microsoft Expression Blend
This walkthrough steps you through the process of creating a WPF customized button using Microsoft Expression Blend.
Observação importante: |
---|
Microsoft Expression Blend works by generating Extensible Application Markup Language (XAML) that is then compiled to make the executable program. If you would rather work with Extensible Application Markup Language (XAML) directly, there is another walkthrough that creates the same application as this one using Extensible Application Markup Language (XAML) with Visual Studio rather than Blend. Consulte Demonstra Passo a passo: Criar um botão usando XAML para obter mais informações. |
The following illustration shows the customized button that you will create.
Convert a Shape to a Button
In the first part of this walkthrough you create the custom look of the custom button. To do this, you first convert a rectangle to a button. You then add additional shapes to the template of the button, creating a more complex looking button. Why not start with a regular button and customize it? Because a button has built-in functionality that you do not need; for custom buttons, it is easier to start with a rectangle.
To create a new project in Expression Blend
Start Expression Blend. (Click Start, point to All Programs, point to Microsoft Expression, and then click Microsoft Expression Blend.)
Maximize the application if needed.
No menu File, clique em New Project.
Select Standard Application (.exe).
Name the project CustomButton and press OK.
At this point you have a blank WPF project. You can press F5 to run the application. As you might expect, the application consists of only a blank window. Next, you create a rounded rectangle and convert it into a button.
To convert a Rectangle to a Button
Defina a propriedade plano de fundo da janela em preto: selecionar a janela, clicar no Guia Propriedadese o conjuntoBackground propriedade para Black.
Desenhe um retângulo aproximadamente do dimensionar de um botão na janela de: selecionar a ferramenta retângulo no painel esquerdo da ferramenta e arrastar o retângulo para a janela.
Complementam os cantos do retângulo: arrastar os pontos de controle de retângulo ou conjunto diretamente o RadiusX e RadiusY Propriedades. Set the values of RadiusX and RadiusY to 20.
alterar o retângulo em um botão: selecionar o retângulo. On the Tools menu, click Make Button.
Especifique o escopo de estilo/modelo: Uma caixa de diálogo semelhante à seguinte é exibida.
For Resource name (Key), select Apply to all. This will make the resulting style and button template apply to all objects that are buttons. For Define in, select Application. This will make the resulting style and button template have scope over the entire application. When you set the values in these two boxes, the button style and template apply to all buttons within the entire application and any button you create in the application will, by default, use this template.
Edit the Button Template
You now have a rectangle that has been changed to a button. In this section, you'll modify the template of the button and further customize how it looks.
To edit the button template to change the button appearance
Vá para o modo de modelo de edição: Para personalizar ainda mais a aparência de nosso botão, é necessário edição o modelo de botão. This template was created when we converted the rectangle into a button. To edit the button template, right-click the button and select Edit Control Parts (Template) and then Edit Template.
In the template editor, notice that the button is now separated into a Rectangle and the ContentPresenter. The ContentPresenter is used to present content within the button (for example, the string "Button"). Both the rectangle and ContentPresenter are laid out inside of a Grid.
Altere os nomes dos componentes de modelo: clicar com o botão direito do mouse no retângulo no modelo de estoque, altere o Rectanglenome de "[Rectangle]" para "outerRectangle" e "myContentPresenter" alterar "[ContentPresenter]".
Altere o retângulo para que ela está vazia dentro (como uma rosca): selecionar outerRectangle and conjunto Fillcomo "transparente" e StrokeThickness para 5.
Then set the Stroke to the color of whatever the template will be. To do this, click the small white box next to Stroke, select CustomExpression, and type "{TemplateBinding Background}" in the dialog box.
Crie um retângulo interno: Agora, criar outro retângulo (nome "innerRectangle") e posicione-simetricamente no interior da outerRectangle . For this kind of work, you will probably want to zoom to make the button larger in the editing area.
Observação: O retângulo pode parecer diferente no (a Figura Por exemplo, Ele pode ter cantos arredondados).
**Mova ContentPresenter para cima:**Neste ponto, é possível que o texto "botão" não estará visível mais. If this is so, this is because innerRectangle is on top of the myContentPresenter. To fix this, drag myContentPresenter below innerRectangle. Reposition rectangles and myContentPresenter to look similar to below.
Observação: Alternatively, you can also position myContentPresenter on top by right-clicking it and pressing Send Forward.
alterar a aparência de innerRectangle: conjunto o RadiusX, RadiusY, e StrokeThickness valores para 20. Além disso, conjunto o Fillpara o plano de fundo do modelo usando a expressão personalizada "{TemplateBinding Background}") e conjunto Strokepara "transparente". Notice that the settings for the Fill and Stroke of innerRectangle are the opposite of those for outerRectangle.
Adicione uma camada de efeito de transparência na parte superior: A parte final de personalizar a aparência do botão é adicionar uma camada de efeito de transparência na parte superior. This glass layer consists of a third rectangle. Because the glass will cover the entire button, the glass rectangle is similar in dimensions to the outerRectangle. Therefore, create the rectangle by simply making a copy of the outerRectangle. Highlight outerRectangle and use CTRL+C and CTRL+V to make a copy. Name this new rectangle "glassCube".
Reposicione glassCube se necessário: If glassCube já não está posicionado para que ela abrange todo o botão, arrastar-o até a posição desejada.
GlassCube oferecem uma forma um pouco diferente de outerRectangle: Alterar as propriedades de glassCube. Start off by changing the RadiusX and RadiusY properties to 10 and the StrokeThickness to 2.
Tornar glassCube aparência de efeito de transparência: conjunto o Fill para uma aparência glassy usando um gradiente linear ou seja, 75 % opaco e alterna entre a cor branco e transparente em intervalos com espaçamento uniforme aproximadamente 6. This is what to set the gradient stops to:
Parar de gradiente 1: Branco com valor de alfa igual a 75 %
Parar de gradiente 2: Transparente
Parar de gradiente 3: Branco com valor de alfa igual a 75 %
Parar de gradiente 4: Transparente
Parar de gradiente 5: Branco com valor de alfa igual a 75 %
Parar de gradiente 6: Transparente
This creates a "wavy" glass look.
Ocultar a camada de efeito de transparência: Agora que ver a aparência da camada glassy, vá para o Painel Aparência of the Painel de propriedades e conjunto opacidade % 0 para ocultá-lo. In the sections ahead, we'll use property triggers and events to show and manipulate the glass layer.
Customize the Button Behavior
At this point, you have customized the presentation of the button by editing its template, but the button does not react to user actions as typical buttons do (for example, changing appearance upon mouse-over, receiving focus, and clicking.) The next two procedures show how to build behaviors like these into the custom button. We'll start with simple property triggers, and then add event triggers and animations.
To set property triggers
criar um novo disparar de propriedade: Com glassCube selecionado, clicar + Propriedade in the Disparadores painel (consulte a figura a seguir a próxima etapa). This creates a property trigger with a default property trigger.
Torna IsMouseOver a propriedade usada pelo disparar: Altere a propriedade para IsMouseOver. This makes the property trigger activate when the IsMouseOver property is true (when the user points to the button with the mouse).
IsMouseOver aciona a opacidade de 100 % para glassCube: Observe que o disparar de gravação está em (consulte a figura anterior). This means that any changes you make to the property values of glassCube while recording is on will become an action that takes place when IsMouseOver is true. While recording, change the Opacity of glassCube to 100%.
You have now created your first property trigger. Notice that the Triggers panel of the editor has recorded the Opacity being changed to 100%.
Press F5 to run the application, and move the mouse pointer over and off the button. You should see the glass layer appear when you mouse-over the button and disappear when the pointer leaves.
alterar de valor de traçado IsMouseOver disparadores: Vamos associar algumas outras ações com o IsMouseOver disparar. While recording continues, switch your selection from glassCube to outerRectangle. Then set the Stroke of outerRectangle to the custom expression of "{DynamicResource {x:Static SystemColors.HighlightBrushKey}}". This sets the Stroke to the typical highlight color used by buttons. Press F5 to see the effect when you mouse over the button.
IsMouseOver dispara texto desfocado: Vamos associar uma ação mais à IsMouseOver disparar de propriedade. Make the content of the button appear a little blurry when the glass appears over it. To do this, we can apply a blur BitmapEffect to the ContentPresenter (myContentPresenter).
Observação: Para retornar a Painel de propriedades volta para o que estava antes de você fez a procura por BitmapEffect, desmarcar o texto dos Caixa de Pesquisar.
At this point, we have used a property trigger with several associated actions to create highlighting behavior for when the mouse pointer enters and leaves the button area. Another typical behavior for a button is to highlight when it has focus (as after it is clicked). We can add such behavior by adding another property trigger for the IsFocused property.
criar disparar de propriedade para IsFocused: Usando o mesmo procedimento para IsMouseOver (consulte a primeira etapa desta seção), criar outro disparar de propriedade para o IsFocused propriedade. While Trigger recording is on, add the following actions to the trigger:
As the final step in this walkthrough, we will add animations to the button. These animations will be triggered by events—specifically, the MouseEnter and Click events.
To use event triggers and animations to spice up behavior
criar um disparar de eventos MouseEnter: Adicione um novo disparar de evento e selecionar MouseEnter sistema autônomo o evento para usar no disparar.
criar uma linha do tempo da animação: Em seguida, associar um linha do tempo de animação para o MouseEnter evento.
After you press OK to create a new timeline, a Timeline Panel appears and "Timeline recording is on" is visible in the design panel. This means we can start recording property changes in the timeline (animate property changes).
Observação: You may need to resize your window and/or panels to see the display.
Crie um quadro-chave: Para criar uma animação, selecionar o objeto que você deseja animar, criar dois ou mais quadros-chave na linha da tempo e para os quadros-chave, defina os valores de propriedade que você deseja que a animação para interpolar entre. The following figure guides you through the creation of a keyframe.
reduzir glassCube nesse quadro-chave: Com o quadro-segundo chave selecionado, diminuir o dimensionar do glassCube 90 % do dimensionar total usando o Transformação de dimensionar.
Pressione F5 para executar o aplicativo. Move the mouse pointer over the button. Notice that the glass layer shrinks on top of the button.
Criar outro disparar de eventos e associá-la uma animação diferentes: Vamos adicionar uma animação mais. Use a similar procedure to what you used to create the previous event trigger animation:
For this timeline, create two keyframes, one at 0.0 seconds and the second one at 0.3 seconds.
With the keyframe at 0.3 seconds highlighted, set the Rotate Transform Angle to 360 degrees.
- Pressione F5 para executar o aplicativo. Clique no botão. Notice that the glass layer spins around.
Conclusão
You have completed a customized button. You did this using a button template that was applied to all buttons in the application. If you leave the template editing mode (see the following figure) and create more buttons, you will see that they look and behave like your custom button rather than like the default button.
Pressione F5 para executar o aplicativo. Click the buttons and notice how they all behave the same.
Remember that while you were customizing the template, you set the Fill property of innerRectangle and the Stroke property outerRectangle to the template background ({TemplateBinding Background}). Because of this, when you set the background color of the individual buttons, the background you set will be used for those respective properties. Try changing the backgrounds now. In the following figure, different gradients are used. Therefore, although a template is useful for overall customization of controls like button, controls with templates can still be modified to look different from each other.
In conclusion, in the process of customizing a button template you have learned how to do the following in Microsoft Expression Blend:
Customize the look of a control.
Set property triggers. Property triggers are very useful because they can be used on most objects, not just controls.
Set event triggers. Event triggers are very useful because they can be used on most objects, not just controls.
Create animations.
Miscelânea: criar gradientes, adicionar BitmapEffects, usar transformações e conjunto propriedades básicas de objetos.
Consulte também
Tarefas
Demonstra Passo a passo: Criar um botão usando XAML