Demonstra Passo a passo: Create a Button by Using Microsoft Expression Blend
Este passo a passo orienta durante o processo de criação de um WPF um botão personalizado usando o Microsoft Expression Blend.
Importante |
---|
Microsoft Expression Blend funciona por meio da geração Extensible Application Markup Language (XAML) que é então compilado para fazer o programa executável.Se você preferir trabalhar com Extensible Application Markup Language (XAML) diretamente, não há outra explicação passo a passo que cria o mesmo aplicativo que isso usando um Extensible Application Markup Language (XAML) com Visual Studio em vez de mistura.See Demonstra Passo a passo: Criar um botão usando XAML for more information. |
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.
On the File menu, click 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 de plano de fundo da janela em preto: Selecione a janela, clique no Guia de propriedadese defina a Background propriedade para Black.
Desenhe um retângulo, aproximadamente do tamanho de um botão na janela: Selecione a ferramenta retângulo no painel esquerdo de ferramenta e arraste o retângulo para a janela.
Arredondar cantos do retângulo: Arraste os pontos de controle de retângulo ou definir diretamente as RadiusX e RadiusY Propriedades. Set the values of RadiusX and RadiusY to 20.
Altere o retângulo em um botão: Selecione o retângulo. On the Tools menu, click Make Button.
Especifica o escopo do estilo/modelo: Aparece uma caixa de diálogo semelhante à seguinte.
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 a exibição do modelo de edição: Para personalizar a aparência do nosso botão, precisamos editar 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 do modelo: Clique com o botão direito do retângulo do estoque de modelo, altere o Rectangle nome de "[Rectangle]" "outerRectangle" e "[ContentPresenter]" da alteração para "myContentPresenter".
Altere o retângulo para que ela está vazia dentro (como uma rosca): Selecione outerRectangle e Fill como "Transparent" 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, crie 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
Your rectangle might look different than the one in the figure (for example, it might have rounded corners).
Mova o ContentPresenter para cima: Neste ponto, é possível que o texto "Button" não será 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.
Altere a aparência de innerRectangle: Definir o RadiusX, RadiusY, e StrokeThickness valores para 20. Além disso, definir o Fill no plano de fundo do modelo usando a expressão personalizada "{fundo TemplateBinding}" ) e defina Stroke para "transparente". Notice that the settings for the Fill and Stroke of innerRectangle are the opposite of those for outerRectangle.
Adicione uma camada de glass na parte superior: A peça final do Personalizando a aparência do botão é adicionar uma camada de glass 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".
Se necessário, reposicione glassCube: Se glassCube é ainda não posicionado de forma que cubra a todo o botão, arraste para a posição.
Dar a uma forma ligeiramente diferente de outerRectangle de glassCube: Alterar as propriedades de glassCube. Start off by changing the RadiusX and RadiusY properties to 10 and the StrokeThickness to 2.
Fazer com que glassCube a aparência de vidro: Definir o Fill para uma aparência glassy usando um gradiente linear, que é opaco de 75% e alterna entre a cor branco e transparente, através de intervalos de aproximadamente uniformemente espaçados 6. This is what to set the gradient stops to:
Limite de gradiente 1: Branco com valor de alfa de 75 %
Limite de gradiente 2: Transparente
Limite de gradiente 3: Branco com valor de alfa de 75 %
Limite de gradiente 4: Transparente
Limite de gradiente 5: Branco com valor de alfa de 75 %
Limite de gradiente 6: Transparente
This creates a "wavy" glass look.
Ocultar a camada de glass: Agora que você ver a aparência de camada de glassy, vá para o painel Aparência do o painel de propriedades e defina a opacidade em 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
Crie um novo disparador de propriedade: Com glassCube selecionada, clique em + propriedade na disparadores painel (consulte a figura a seguir a próxima etapa). This creates a property trigger with a default property trigger.
Verifique a propriedade usada pelo disparador de IsMouseOver: 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 dispara a opacidade de 100% para glassCube: Observe que o a gravação do disparador 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.
Alteração do valor de traçado de disparadores de IsMouseOver: Vamos associar algumas outras ações com o IsMouseOver disparador. 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 manchado: Vamos associar uma ação mais para o IsMouseOver disparador 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
To return the Properties panel back to what it was before you did the search for BitmapEffect, clear the text from the Search box.
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.
Crie o disparador de propriedade para IsFocused: Usando o mesmo procedimento para IsMouseOver (consulte a primeira etapa desta seção), criar outro disparador 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.
Usar animações e disparadores de eventos para adicionar interatividade
Crie um disparador de evento de MouseEnter: Adicione um novo disparador de evento e selecione MouseEnter como o evento para usar no disparador.
Crie um cronograma de animação: Em seguida, associar um cronograma de animação para o MouseEnter de 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, selecione o objeto que você deseja animar, criar duas ou mais quadros principais na linha da tempo e para os quadros-chave, defina os valores de propriedade que você deseja que a animação interpolará entre. The following figure guides you through the creation of a keyframe.
GlassCube de redução neste quadro-chave: Com o segundo quadro-chave selecionado, reduzir o tamanho da glassCube a 90% de seu tamanho máximo de usando o Tamanho transformar.
Press F5 to run the application. Move the mouse pointer over the button. Notice that the glass layer shrinks on top of the button.
Criar outro disparador de eventos e associar 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.
- Press F5 to run the application. Click the button. Notice that the glass layer spins around.
Conclusion
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.
Press F5 to run the application. 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 o BitmapEffects, usar transformações e defina as propriedades básicas de objetos.
Consulte também
Tarefas
Demonstra Passo a passo: Criar um botão usando XAML