Silverlight事件處理相關(guān)操作指南
Silverlight事件處理是一個初學(xué)者們最為重要的一個學(xué)習(xí)過程。對于這方面的知識點。我們將會在文章中給出正確的介紹,希望對于剛剛學(xué)習(xí)者款工具的朋友有所幫助,提高自己的開發(fā)效率。#t#
對于Silverlight DOM對象的事件處理比較簡單,首先在對應(yīng)的XAML文件中為事件源對象和目標(biāo)對象聲明x:Name屬性,然后在XAML的代碼后置類中通過使用該屬性的值就可對該對象進(jìn)行完全控制,當(dāng)然需要為事件源對象附加一個對應(yīng)的事件。
對于由HTML元素觸發(fā)的事件要相對復(fù)雜一些,首先需在XAML的代碼后置類中通過HtmlPage.Document.GetElementByID("ElementID")獲取該元素對象,然后為該對象附加一個事件,再在對應(yīng)的事件處理方法中就可進(jìn)行事件的處理。
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事件處理的相關(guān)概念就為大家介紹到這里。