Tải bản đầy đủ (.pdf) (7 trang)

Lập trình .net 4.0 và visual studio 2010 part 51 ppt

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (247.93 KB, 7 trang )

CHAPTER 14  SILVERLIGHT INTRODUCTION

345
Simple Animation
Silverlight allows you to animate objects both declaratively and programmatically. Animation is perhaps
easier to understand programmatically, so you will create a very simple animation to move a rectangle
across a screen and at the same time change its transparency by modifying its opacity.
You will use a Storyboard class to create an animation. The Storyboard defines what will happen
within the animation (the story) and contains features to start, stop, and repeat the animation.
The storyboard has a property called Interval that is a timer that allows you to perform the
animation. In the example when the storyboard interval occurs, you will increment the x and y position
of the rectangle and increase the opacity.
Creating Animation Programmatically
Let's start the example:
1. Create a new folder called Animation within your project.
2. Right-click this folder➤Add➤New Item➤Silverlight User Control.
3. Call it Animation.
4. Remove the d:DesignHeight="300" d:DesignWidth="400" properties from the user control tag.
5. Replace the Grid tags with the following XAML:
<Canvas Width="900" Height="700" Background="AliceBlue">
<Rectangle Width="52" Height="52" Stroke="#FF000000" Opacity="0" Fill="Red"
x:Name="rectAnimation" RadiusX="10" RadiusY="10" />
</Canvas>
6. Open ~/Animation/Animation.xaml.cs and enter the following code:
public partial class Animation : UserControl
{
Storyboard StoryBoard = new Storyboard();
int Count = 0;

public Animation()
{


this.Loaded += new RoutedEventHandler(Animation_Loaded);
StoryBoard.Completed += new EventHandler(StoryBoard_Completed);
InitializeComponent();
}

public void Animation_Loaded(object sender, RoutedEventArgs e)
{
StoryBoard.Duration = TimeSpan.FromMilliseconds(10);
StoryBoard.Begin();
}

void StoryBoard_Completed(object sender, EventArgs e)
{
Canvas.SetTop(rectAnimation, Count);
Canvas.SetLeft(rectAnimation, Count);
rectAnimation.Opacity = 0.001 * Convert.ToDouble(Count);
CHAPTER 14  SILVERLIGHT INTRODUCTION

346
Count += 1;

StoryBoard.Begin();

if (Count == 100)
StoryBoard.Stop();
}
}
}

7. Now edit MainMenu so you can navigate to this page. Open ~/MainMenu.xaml.cs.

8. In the MainMenu_Loaded() method add a handler for the animation button:

this.cmdAnimation.Click += new RoutedEventHandler(cmdAnimation_Click);
9. Add the code to load Animation.xaml when the animation button is clicked:
void cmdAnimation_Click(object sender, RoutedEventArgs e)
{
PageNavigator.LoadPage(new Animation.Animation());
}
10. Press F5 to run the application.
When the page is loaded you should see a rectangle move diagonally across the screen. Note that
you incremented the Opacity value using the following code:

rectAnimation.Opacity = 0.001 * Convert.ToDouble(Count);

However, when you incremented the Left and Top properties, you had to increment the values
using the following syntax:

Canvas.SetTop(rectAnimation, Count);
Canvas.SetLeft(rectAnimation, Count);

This is because Opacity is not an attached property, but Top and Left are.
Responding to User Events
You will now detect the user clicking the rectangle and then perform a different animation:
1. In Animation_Loaded(), add the following code:
rectAnimation.MouseLeftButtonDown +=
new MouseButtonEventHandler(rectAnimation_MouseLeftButtonDown);
2. Let’s add another storyboard for an animation that will start when the rectangle is clicked. You
will change the rectangle's color to yellow to indicate that it has been clicked and then move it
horizontally instead of diagonally acrosss the screenPixar has nothing to fear. Add a new
Storyboard object within the Animation class:

Storyboard StoryBoard2 = new Storyboard();


CHAPTER 14  SILVERLIGHT INTRODUCTION

347
3. Create the methods rectAnimation_MouseLeftButtonDown() and StoryBoard2_Completed():
void rectAnimation_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
rectAnimation.Fill = new SolidColorBrush(Colors.Yellow);
rectAnimation.Opacity = 1;
StoryBoard.Stop();

StoryBoard2.Completed += new EventHandler(StoryBoard2_Completed);
StoryBoard2.Duration = TimeSpan.FromMilliseconds(10);
StoryBoard2.Begin();
}

void StoryBoard2_Completed(object sender, EventArgs e)
{
Canvas.SetLeft(rectAnimation, Count);
Count += 1;
StoryBoard2.Begin();
}
4. Press F5 to run your application and then click the rectangle. The rectangle should change to
yellow and then move across the screen.
Declarative Animation
Animation can also be declared declaratively. Following is an example produced by Blend 3 for moving a
rectangle horizontally across the screen in two seconds (not the sort of thing you will be writing yourself):


<UserControl.Resources>
<Storyboard x:Name="Storyboard1">
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="rectangle"
Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].
(TranslateTransform.X)">
<SplineDoubleKeyFrame KeyTime="00:00:00" Value="0"/>
<SplineDoubleKeyFrame KeyTime="00:00:02" Value="258"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</UserControl.Resources>

<Grid x:Name="LayoutRoot" Background="White">
<Rectangle Height="80" HorizontalAlignment="Left" Margin="34,123,0,0"
VerticalAlignment="Top" Width="91" Fill="#FFE24646" Stroke="#FF000000"
x:Name="rectangle" RenderTransformOrigin="0.5,0.5">
<Rectangle.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform/>
<TranslateTransform/>
</TransformGroup>
</Rectangle.RenderTransform>
</Rectangle>
</Grid>
CHAPTER 14  SILVERLIGHT INTRODUCTION

348
Although the preceding XAML is not as readable as animating the item programmatically, it is
arguably easier to produce. Blend allows you to define key frames for your object and will then animate

between them. For more information about Blend, check out the great tutorial videos available at


Figure 14-10. Blend showing timeline on right and the path the square will move to
HTML Integration
Silverlight has some great functionality that allows you to interact with the web page through something
called the HTML bridge. The HTML bridge allows you to modify DOM elements and call JavaScript
functions from within your Silverlight application. The reverse is also possible, allowing you to call
Silverlight functions from within JavaScript. Note that Silverlight utilizes parts of the DLR (refer to
Chapter 3) to perform some of this functionality (Silverlight was one of the first applications to benefit
from the DLR).
CHAPTER 14  SILVERLIGHT INTRODUCTION

349
Calling a JavaScript Function from Silverlight
Select the Chapter14.HelloSilverlight.Web project:
1. Open ~\Chapter14.HelloSilverlightTestPage.aspx.
2. Add the following code within the page's head tag to show an alert box with the message
parameter you will shortly pass in:
<script type="text/javascript">

function ShowMessage(Message) {
alert(Message);
}

</script>
3. Open ~/MainMenu.xaml.cs.
4. In the MainMenu_Loaded() method, add the following event handler to the cmdCallJS button:
this.cmdCallJS.Click += new RoutedEventHandler(cmdCallJS_Click);
5. Now add the following code:

void cmdCallJS_Click(object sender, RoutedEventArgs e)
{
System.Windows.Browser.HtmlPage.Window.Invoke(
"ShowMessage", "This function was called from Silverlight");
}
6. Press F5 to run your application and click the Call JS button.
You should receive the message “This function was called from Silverlight”.
Changing DOM Element Values from Silverlight
You can manipulate any aspect of the DOM from Silverlight. To demonstrate this feature, add a text box
with ID txtHelloFromSilverlight to Chapter14.HelloSilverlightTestPage.aspx and utilize the following
code:

System.Windows.Browser.HtmlPage.Document
.GetElementById("txtHelloFromSilverlight")
.SetProperty("value", "Hello from Silverlight");
Calling a Silverlight Function from JavaScript
It is also possible to call Silverlight functions from JavaScript. Because this has some security risks, you
have to tell Silverlight you want to expose functions to JavaScript:
1. Add the following function to ~/MainMenu.xaml.cs, which you will shortly expose:
public string CallMeFromJS()
{
return "Silverlight function called from JS";
}
CHAPTER 14  SILVERLIGHT INTRODUCTION

350
2. Add the following attribute to the CallMeFromJS() method:
[System.Windows.Browser.ScriptableMember()]

Your function should look like this:


[System.Windows.Browser.ScriptableMember()]
public string CallMeFromJS()
{
return "Silverlight function called from JS";
}

NOTE
You can also add the [System.Windows.Browser.ScriptableType] attribute to the whole class to
make all public methods accessible via JavaScript. Be careful with this, though, because it can have security
implications.
Before you can call this function, you need to register the function for JavaScript’s use.
1. Add the following code at the end of the Application_Startup event in ~\App.xaml.cs.
//Set up client side access to function within Main Menu
System.Windows.Browser.HtmlPage.RegisterScriptableObject("MainMenu", new MainMenu());
2. Add the following code inside the head tag in Chapter14.HelloSilverlightTestPage.aspx to call
the method when the Silverlight plug-in is loaded:
<script type="text/javascript">
function Silverlight_PluginLoaded(sender)
{
silverlightControl = document.getElementById("silverlightObject");
alert(silverlightControl.Content.MainMenu.CallMeFromJS());
}
</script>
3. Add an id property to the Silverlight object tag:
id="silverlightObject"
4. Add a new parameter to tell the Silverlight plug-in the JavaScript function to call when it is
loaded:
<param name="onLoad" value="Silverlight_PluginLoaded" />
5. Press F5 to run your application; you should see an alert box pop up with the text “Silverlight

function called from JS”.
Unless you want an alert box popping up throughout the rest of this chapter (which would be pretty
irritating), it is probably a good idea to remove the onLoad param from the Silverlight control now.
Silverlight has extensive functionality for interacting with the web page. For more information, refer to
Mike Taulty’s excellent blog at
archive/2008/10/15/10836.aspx.
CHAPTER 14  SILVERLIGHT INTRODUCTION

351
Passing Parameters into Silverlight
There are a number of different methods for passing parameters into Silverlight:
• Query string
• InitParams property
• JavaScript function calls (as explained previously)
InitParams
The easiest way to pass parameters into a Silverlight application is with the InitParams property on the
Silverlight control. Values passed in using this method need to be represented in the format
Name=Value and separated by commas. For example:

Name=Alex,Age=28,Country=Australia

To use the IntitParams property, just add params to the object tag like so:

<param name="InitParams" value="name=alex,sex=male" />

Input values can then be retrieved by iterating through the InitParams keys collection in
App.xaml.cs:

//Initialization parameters.
foreach (String key in e.InitParams.Keys)

{
string strKey = key;
string strValue=e.InitParams[key];
}
Query String
Another method of passing paramaters to a Silverlight is with the query string. The following code shows
you how to iterate through all the query string values:

//URL Params
foreach (String key in System.Windows.Browser.HtmlPage.Document.QueryString.Keys)
{
string KeyName = key;
string strValue=System.Windows.Browser.HtmlPage.Document.QueryString[key];
}
Embedding Content in a Silverlight application
If you want to utilize content such as images within your Silverlight application, you have a number of
options, two of which are shown here:
• Relative rath + resource:
<Image Source="myImage.jpg"></Image>

×