对于Silverlight DOM对象的事件处理比较简单,首先在对应的XAML文件中为事件源对象和目标对象声明x:Name属性,然后在XAML的代码后置类中通过使用该属性的值就可对该对象进行完全控制,当然需要为事件源对象附加一个对应的事件。
对于由HTML元素触发的事件要相对复杂一些,首先需在XAML的代码后置类中通过HtmlPage.Document.GetElementByID("ElementID")获取该元素对象,然后为该对象附加一个事件,再在对应的事件处理方法中就可进行事件的处理。
演示代码如下:
XAML文件源代码:
1
<Canvas x:Name="parentCanvas"
2
xmlns="http://schemas.microsoft.com/client/2007"
3
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4
Loaded="Page_Loaded"
5
x:Class="SilverlightStudy.Page;assembly=ClientBin/SilverlightStudy.dll"
6
Width="300"
7
Height="100"
8
Background="White"
9
>
10
<Canvas Width="300" Height="100" Canvas.Top="0" Canvas.Left="0">
11
<Canvas.Background>
12
<SolidColorBrush Color="PaleGreen"></SolidColorBrush>
13
</Canvas.Background>
14
<Rectangle Canvas.Left="0" Width="120" Height="40" Stroke="Blue" StrokeThickness="3">
15
<Rectangle.Fill>
16
<LinearGradientBrush>
17
<GradientStop Color="Yellow" Offset="0.2"/>
18
<GradientStop Color="Orange" Offset="0.5"/>
19
<GradientStop Color="Red" Offset="0.8"/>
20
</LinearGradientBrush>
21
</Rectangle.Fill>
22
</Rectangle>
23
<TextBlock x:Name="MyTextBlock" FontFamily="Arial" Cursor="Hand" FontSize="30" Foreground="Blue" Canvas.Left="0" Canvas.Top="0" Text="Button1"></TextBlock>
24
<TextBlock x:Name="ShowText" FontFamily="Arial" Canvas.Left="0" Canvas.Top="60" FontSize="30">
25
<TextBlock.Foreground>
26
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
27
<GradientStop Color="Yellow" Offset="0.3"/>
28
<GradientStop Color="Orange" Offset="0.5"/>
29
<GradientStop Color="Red" Offset="0.8"/>
30
</LinearGradientBrush>
31
</TextBlock.Foreground>
32
</TextBlock>
33
</Canvas>
34
</Canvas>
XAML.CS文件源代码:
2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34








































1.单击Button1的效果

2.点击按钮2的效果

遗憾的是好像Silverlight1.1还是不直接支持中文。