Silverlight事件处理是一个初学者们最为重要的一个学习过程。对于这方面的知识点。我们将会在文章中给出正确的介绍,希望对于刚刚学习者款工具的朋友有所帮助,提高自己的开发效率。#t#
对于Silverlight DOM对象的事件处理比较简单,首先在对应的XAML文件中为事件源对象和目标对象声明x:Name属性,然后在XAML的代码后置类中通过使用该属性的值就可对该对象进行完全控制,当然需要为事件源对象附加一个对应的事件。
对于由HTML元素触发的事件要相对复杂一些,首先需在XAML的代码后置类中通过HtmlPage.Document.GetElementByID("ElementID")获取该元素对象,然后为该对象附加一个事件,再在对应的事件处理方法中就可进行事件的处理。
Silverlight事件处理演示代码如下:
XAML文件源代码:
- < Canvas x:Name="parentCanvas"
- xmlns="http://schemas.microsoft.com
/client/2007"- xmlns:x="http://schemas.microsoft.
com/winfx/2006/xaml"- Loaded="Page_Loaded"
- x:Class="SilverlightStudy.Page;assembly
=ClientBin/SilverlightStudy.dll"- Width="300"
- Height="100"
- Background="White"
- >
- < Canvas Width="300" Height="100"
Canvas.Top="0" Canvas.Left="0">- < Canvas.Background>
- < SolidColorBrush Color="PaleGreen">
- < /SolidColorBrush>
- < /Canvas.Background>
- < Rectangle Canvas.Left="0"
Width="120" Height="40" Stroke=
"Blue" StrokeThickness="3">- < Rectangle.Fill>
- < LinearGradientBrush>
- < GradientStop Color="Yellow" Offset="0.2"/>
- < GradientStop Color="Orange" Offset="0.5"/>
- < GradientStop Color="Red" Offset="0.8"/>
- < /LinearGradientBrush>
- < /Rectangle.Fill>
- < /Rectangle>
- < TextBlock x:Name="MyTextBlock"
FontFamily="Arial" Cursor="Hand"
FontSize="30" Foreground="Blue"
Canvas.Left="0" Canvas.Top="0"
Text="Button1">< /TextBlock>- < TextBlock x:Name="ShowText"
FontFamily="Arial" Canvas.Left="0"
Canvas.Top="60" FontSize="30">- < TextBlock.Foreground>
- < LinearGradientBrush
StartPoint="0,0" EndPoint="0,1">- < GradientStop Color="Yellow" Offset="0.3"/>
- < GradientStop Color="Orange" Offset="0.5"/>
- < GradientStop Color="Red" Offset="0.8"/>
- < /LinearGradientBrush>
- < /TextBlock.Foreground>
- < /TextBlock>
- < /Canvas>
- < /Canvas>
Silverlight事件处理之XAML.CS文件源代码:
- using System;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Documents;
- using System.Windows.Ink;
- using System.Windows.Input;
- using System.Windows.Media;
- using System.Windows.Media.Animation;
- using System.Windows.Shapes;
- using System.Windows.Browser;
- namespace SilverlightStudy
- {
- public partial class Page : Canvas
- {
- private HtmlDocument document;
- public void Page_Loaded(object o, EventArgs e)
- {
- // Required to initialize variables
- InitializeComponent();
- document = HtmlPage.Document;
- HtmlElement MyButton = document.
GetElementByID("MyButton");- bool ec1 = MyButton.AttachEvent(
"onclick", new EventHandler(this
.OnMyButtonClicked));- MyTextBlock.MouseLeftButtonDown+=new
MouseEventHandler(MyTextBlock_
MouseLeftButtonDown);- }
- void MyTextBlock_MouseLeftButtonDow
n(object sender, MouseEventArgs e)- {
- //throw new NotImplementedException();
- ShowText.Text = "This is Button1";
- }
- private void OnMyButtonClicke
d(object sender, EventArgs e)- {
- ShowText.Text = "This is Button2";
- }
- }
- }
Silverlight事件处理的相关概念就为大家介绍到这里。