Tutorial - Introdução ao Silverlight 2 (Olá Mundo) Tutorial - Introduction to Silverlight 2 (Hello World)
Últimamente muito se tem falado sobre Silverlight, a aposta da Microsoft para concorrer com o flash da Macromedia. Últimamente has been much talked about Silverlight, Microsoft's bet to compete with the flash of Macromedia. A primeira versão do Silverlight baseava-se muito na utilização de javascript e era muito complexo implementar aplicações que fossem relativamente complicadas. The first version of Silverlight based on the very use of javascript was very complex and implement applications that were relatively complicated. A versão 2 do Silverlight veio alterar todo este paradigma, pois foram aproveitadas as capacidades do .NET para desenvolver as aplicações Silverlight 2. The version 2 of Silverlight this whole paradigm has changed, as they were exploited the capabilities of. NET to develop the applications Silverlight 2. Agora podemos utilizar C# para desenvolver Silverlight, e dispomos de um conjunto alargados de controlos que nos facilitam em muito o desenvolvimento. Now we can use C # to develop Silverlight, and have an expanded set of controls that we facilitate the development in much. Neste tutorial vou explicar como criar uma aplicação muito simples em Silverlight 2, para se ambientarem a esta nova plataforma. In this tutorial I will explain how to create a very simple implementation in Silverlight 2, to ambientarem to this new platform.
O que é o Silverlight 2.0 What is Silverlight 2.0
O Silverlight 2.0 é uma plataforma que nos permite desenvolver aplicações ricas para a internet (RIAS - Rich Internet Applications). The Silverlight 2.0 is a platform that allows us to develop rich applications for the Internet (RIAS - Rich Internet Applications). Tal como o flash, também é necessário instalar um plugin no browser para correr aplicações Silverlight. As the flash is also necessary to install a plug-in browser to run Silverlight applications. Este pequeno plugin, contém uma versão reduzida da plataforma .NET. This small plug, contains a smaller version of the platform. NET.
As capacidades do Silverlight 2.0 são enormes e vão desde reproduzir vídeos de alta qualidade até à construção de aplicações complexas, como por exemplo uma aplicação de análise do mercado bolsista. The capabilities of Silverlight 2.0 are enormous and range from high-quality videos play until the construction of complex applications, such as application of an analysis of the stock market. As aplicações Silverlight usam uma linguagem denominada de XAML . The Silverlight applications using a language called Extensible Application Markup Language. É com esta linguagem que nós vamos definir a interface da nossa aplicação Silverlight. It is with this language that we will define the interface of our application Silverlight. A lógica da aplicação (code-behind) pode ser construída utilizando C# ou VB. The logic of the application (code-behind) can be built using C # or VB.
Tutorial - Olá Silverlight 2.0 Tutorial - Hello Silverlight 2.0
Agora que já temos uma ideia do que é o Silverlight 2.0, vamos prosseguir com o tutorial, onde vamos criar uma aplicação do tipo "Olá Mundo!". Now we have an idea of what is the Silverlight 2.0, we will continue with the tutorial, where we will create an implementation of the "Hello World!".
Antes de começarmos com o tutorial propriamente dito, necessitamos de ter o nosso ambiente de desenvolvimento preparado para desenvolvermos aplicações Silverlight 2.0. Before we start with the tutorial itself, we need to have our development environment, prepared to develop applications Silverlight 2.0. Para isso existem alguns pré-requisitos: For this there are some preconditions:
Para desenvolvermos aplicações Silverlight 2.0 necessitamos de um computador com o Visual Studio 2008 e as Silverlight Tools instaladas. To develop applications Silverlight 2.0 need a computer with Visual Studio 2008 and the Silverlight Tools installed. Podem consultar este artigo para saberem como instalar as Silverlight Tools: They can consult this article to know how to install the Silverlight Tools:
http://www.istomesmo.com/2008/03/19/tutorial-instalar-as-silverlight-tools-beta-1-for-visual-studio-2008/ http://www.istomesmo.com/2008/03/19/tutorial-instalar-as-silverlight-tools-beta-1-for-visual-studio-2008/
O Microsoft Expression Blend eo Deep Zoom Composer são componentes opcionais, não são necessários para o âmbito deste tutorial, mas poderão investigá-los se quiserem construir aplicações mais complexas. Microsoft Expression Blend and Deep Focus Composer are optional components, are not necessary for the scope of this tutorial, but may investigate them if they want to build more complex applications.
Assumindo que já têm todos os componentes instalados vamos iniciar o tutorial, abrindo o Visual Studio 2008 e criando um novo projecto do tipo Silverlight. Assuming that all components are already installed we will start the tutorial, opening the Visual Studio 2008 and creating a new project of the type Silverlight.
Quando criamos um novo projecto do tipo Silverlight 2.0, somos questionados se desejamos criar um projecto web para alojar/testar o projecto Silverligth. When we created a new type of project Silverlight 2.0, we asked if we wish to create a web project for housing / Silverligth test the project. Para este tutorial vamos dizer que sim, e que queremos um projecto web do tipo "Web Application". For this tutorial we will say that yes, and we want to project a web-type "Web Application".
Como podemos ver pela imagem seguinte, a nossa solução é constituída por uma aplicação web, onde será alojado o nosso projecto Silverlight, e pelo projecto Silverlight propriamente dito. As we can see the next image, our solution is a web application, which will be hosted our project Silverlight, and the Silverlight project itself. O projecto Silverlight é consituído por duas página XAML, a App.xaml ea Page.xaml . The project is Silverlight consituído by two page Extensible Application Markup Language, the App.xaml and Page.xaml.
Para este tutorial vamos apenas focar-nos na Page.xaml , que é a que é aberta por omissão na área de trabalho quando criamos a solução. For this tutorial we will only focus on the Page.xaml, the one that is open by default on the desktop when we create the solution.
Na parte de baixo do Visual Studio, temos o código XAML da nossa página Silverlight, que inicialmente é constituída por um usercontrol e um layout do tipo Grid. At the bottom of Visual Studio, we have the code of our Silverlight Extensible Application Markup Language, which initially consists of a usercontrol and a layout of the type Grid. Dentro da Grid vamos criar um botão adicionando o código seguinte: Inside the Grid we will create a button adding the following code:
O atributo x:Name indica o nome do botão, o Width indica a largura, o Height a altura eo Content é o texto que aparece no botão. The attribute x: Name indicates the name of the button, the Width indicates the width, height and the Height Content is the text that appears on the button.

Neste momento temos o nosso botão criado. We now have our button created. Se quiserem podem correr a solução, e já vão conseguir ver o botão. If they want can run the solution, and we will see the button. Já temos o botão, agora vamos adicionar o evento click, para alterar o seu texto quando lhe clicarmos. We already have the button, we will now add the event click, to change its text when it clicarmos. Para isso vamos adicionar mais um atributo ao botão: To do this we will add one more attribute to the button:

Quando adicionamos o atributo click, o Visual Studio 2008 dá-nos logo a opção de associarmos um Event Handler ao evento Click , bastando para isso clicar na tecla Enter . When we add the attribute click, Visual Studio 2008 gives us the option to immediately associate an Event Handler Click the event, if we simply click on the Enter key. Quando clicamos no Enter , o Visual Studio cria o Event Handler no codeBehind da Page.xaml . When clicamos in Enter, Visual Studio creates the Event Handler in codeBehind of Page.xaml.

Vamos então passar para o codeBehind da página, clicando com o botão direito do rato sobre a área de design e escolhendo a opção " View Code ". We will then move to the codeBehind of the page by clicking the right mouse button over the area of design and choosing the option "View Code". No codeBehind, já temos a função btnHello_Click . In codeBehind, we already have the function btnHello_Click.

Na função do click do botão, vamos criar a lógica para alterar o texto do mesmo, cada vez que este é clicado. In light of the click of the button, we will create the rationale for amending the text of that, each time this is clicked. adicionando o código seguinte: adding the following code:

Se corrermos a aplicação, quando clicamos no botão, o seu texto vai alternar entre " Clica aqui " e " Olá Silverlight 2! ". If running the application, when clicamos the button, the text vai switch between "Click here" and "Hello Silverlight 2!".

Construímos a nossa primeira aplicação Silverlight de forma fácil e rápida, incluindo a utilização de eventos, com toda a comodidade da plataforma .NET C#. We built our first application Silverlight easily and quickly, including the use of events, with all the convenience of the platform. NET C #. ![]()
NOTA: Para a aplicação web apenas é transferido um ficheiro xap que podem encontrar na pasta ClientBin da aplicação Web. NOTE: For the web application is only transferred a file xap who can find the folder ClientBin the application Web
Se tiverem alguma dúvida ou questão deixem comentário em baixo. If you have any questions or comments in question no longer low.
Se gostaram deste artigo subscrevam a feed RSS do istomesmo, para ficarem actualizados sobre os últimos artigos. If you liked this article subscribe to the RSS feed istomesmo, to be updated on the latest articles.
» Subscrevam aqui a fedd RSS « "Subscribe here fedd RSS '
Obtenha mais informações sobre a fedd RSS aqui Learn more about the RSS fedd here


Maio 16th, 2008 at 22:37 May 16th, 2008 at 22:37
Gosto muito do Silverlight. I love much of Silverlight. O Flash ainda está para ficar durante muito tempo , mas programar em C# em vez de ActionScript é outro nível… Flash is yet to be long, but programming in C # instead ActionScript is another level…
Para ver a potência do SL basta ver isto: http://memorabilia.hardrock.com/ To see the power of the SL just see this: http://memorabilia.hardrock.com/
Maio 29th, 2008 at 4:14 May 29th, 2008 at 4:14
Gosto do Flash mas o Silverlight não deixa a desejar…..parabéns pelo tutorial… I love flash but the Silverlight does not want to… .. congratulations on tutorial…
Agosto 4th, 2008 at 23:26 August 4th, 2008 at 23:26
@Pasokon @ Pasokon
O Silverlight ainda está numa fase inicial. The Silverlight is still at an early stage. Tem grandes potencialidades, mas vamos ver se não apareceu tarde demais. It has great potential, but let's see if appeared too late. O flash já está muito implementado. The flash is very implemented.
Agosto 4th, 2008 at 23:28 August 4th, 2008 at 23:28
@Artur Artur @
Concordo plenamente. I fully agree. O exemplo apresentado, dá realmente para ver grande parte da potencialidade do silverlight. The illustrative example, gives really great to see the potential of silverlight. E a comodidade de programar com C# poderá ser determinante na evolução do Silverlight face ao Flash. And the convenience of programming with C # could be decisive in the evolution of Silverlight against the Flash. Vamos ver. Let's see. Só o tempo nos poderá dizer quem será o vencedor. Only time can tell us who will be the winner. Se é que vai haver um. If we have a vai.