silverlight开发篇入门

This item was filled under [ silverlight ]

from:http://silverlight.jc.jishu.me

XAML语法入门

XAML发音”zammel”,以XML为标准格式。在XAML中您可以使用XML描述类的层次结构,可以使用Visual Studio和Expression等工具可视化编辑。其中命名空间、属性、实例对象、事件等,在XAML中进行了约束制定规则。可在Silverlight、XBAP、WPF Application等平台中使用XAML文件,所以见意您详细阅读本章。

<Canvas
xmlns=”http://schemas.microsoft.com/client/2007
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml
Width=”1024″ Height=”768″
x:Name=”rootCanvas”
Loaded=”canvasLoaded”>

图1

一个XAML文件最终描述的是一个类,其中标签名Canvas是XAML文件描述的类继承的控件类名(如果不是默认命名空间,则必须的加上空间的前缀),同时Code中也继承此类。在浏览器中Silverlight作为一个控件的角色加载,所以此处中的Canvas也可以其它的控件比如:Panel,Control基类等。在XBAP中浏览器会把XAML作为页面执行,所以XBAP中的XAML应为Page派生类,在WPF Application中的XAML文件应是Application的派生类。其中属性Width和Height为面板的面积,Loaded为加载事件,其中Window和Height在属性获取时会转换为Int32类型,而Loaded会转换为canvasLoaded的委托。
命名空间

在“图1”的XAML标记中,其中xmlns=”http://schemas.microsoft.com/client/2007“是XAML文件中的默认命名空间,其中http://schemas.microsoft.com/client/2007代表的是一组.Net类库命名空间,包括:“System.Windows 和 System.Windows.Controls”等基本控件命名空间,是XAML处理器进行制定的,所以也会随版本不同而变化。
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml“,其中xmlns:x中的x可以随意用其它字母代替,实现命字空间的声明。在调用此命名空间的成员时使用x:成员名就可以。成员基本包括:“x:Array、x:Class、x:ClassModifier、x:Code、x:FieldModifier、x:Key、x:Name、x:Null、x:Shared、x:Static、x:Subclass、x:Type、x:TypeArguments、x:Uid、x:XData”,由XAML处理器的版本而升级变化。

映射到自定义类和程序集

语法使用下列可能的命名标记和值:

clr-namespace: 在包含要作为元素公开的公共类型的程序集中声明的公共语言运行库 (CLR) 命名空间。

assembly= 是指包含部分或全部引用的 CLR 命名空间的程序集。该值通常只是程序集的名称,而不是路径。该程序集的路径必须在生成编译的 XAML 的项目文件中以项目引用的形式建立。另外,为了合并版本管理和强名称签名,该值也可以是 AssemblyName 定义的字符串。

请注意,分隔 clr-namespace 标记和其值的字符是冒号 (:),而分隔 assembly 标记和其值的字符是等号 (=)。这两个标记之间使用的字符是分号。例如:

xmlns:custom=”clr-namespace:SDKSample;assembly=SDKSampleLibrary.dll”

映射到当前程序集
如果引用的 clr-namespace 是在引用自定义类的应用程序代码所在的程序集中定义的,则可以省略 assembly。这种情况的等效语法是指定 assembly=,等号后不需要任何字符串标记。

如果自定义类是在同一程序集中定义的,则不能将其用作页的根元素。不需要映射分部类;如果您希望在 XAML 中将自定义类作为元素引用,只需要映射应用程序中页的非分部类。
属性
XAML中的属性和XML中的属性一样,只不过XAML对其读取方式不同!比如Width=”2″,其中读取时通过TypeConverter转换为Int32类型了。在标记对象名称的后面使用名称=”值”的格式,在转换时经过三个步骤如下:

1、如果 XAML 处理器遇到一个大括号,或者遇到一个从 MarkupExtension 派生的对象元素,则将首先计算所引用的标记扩展(而不是将该扩展作为字符串来处理),而且将使用由标记扩展返回的对象。在许多情况下,由标记扩展返回的对象将是对现有对象的引用,或者是一个将计算推迟到运行时的表达式,而不是一个新对象。

2、如果该属性 (Property) 是用指定的 TypeConverter 声明的,或者该属性 (Property) 的值类型是用属性 (Attribute) TypeConverter 声明的,则该属性 (Attribute) 的字符串值将作为转换输入提交到类型转换器,该转换器将返回一个新的对象实例。

3、如果没有 TypeConverter,则将尝试直接转换为属性类型。最后一个级别是直接在基元类型之间转换,或者在枚举中检查名称(这将返回匹配的值)。

在没有找到制定的格式将会异常失败!

枚举属性

声明属性时如果类型为Enum(枚举),在XAML中您只需要输入枚举中的成员名称。XAML会通过Enum.Parse方法获取其真正成员,其中类型为“枚举属性类型”中找到其成员名称。多个值可以使用逗号分割,但如果有此添加TypeConverter类型转换器时,则有可能是加号(+)等等区分。

<Trigger Property=”Visibility” Value=”Collapsed,Hidden”>
<Setter … />
</Trigger>

属性元素

由于属性是有多种类型的,可以是String、Int32、自定义类。当一些.Net类中没有TypeConverter转换器时,“属性名=值”方式是表达不了一个类的。也就不可能赋予给属性,所以XAML中提供了元素为属性,格式如下:

<Window
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml
Title=”styles” Height=”265″ Width=”402″>
<Window.Resources>
<Style x:Key=”btnStyle” TargetType=”Button”>
<Style.Setters>
<Setter Property=”Foreground” Value=”Blue”/>
<Setter Property=”Background” Value=”AliceBlue”/>
</Style.Setters>
</Style>
</Window.Resources>
<Button Style=”{StaticResource btnStyle}” Name=”button1″>WPF HOME</Button>
</Window>

图2

这段代码实现了Button的样式功能,其中Style对象要添加到Window.Resources里。其中Window.Resources为标记元素,子标记是赋予的值。

附加属性

附加属性是.Net 3.0中WPF控件中的新面象对象架构,两个控件可以互相使用各自的属性值。通常会子控件使用父控件的属性赋值,并且父控件循环子控件,获取自己属性的值并响应的操作,如图3所示。也可以子控件获取父控件的属性,设为子控件的默认值。

声明附加属性:

public static readonly DependencyProperty TopProperty=DependencyProperty.RegisterAttached(“PropertyName”,ValueType,FromType,defaultPropertyMetadata);

PropertyName:第一个参数为附加属性的名称,用于外部查找使用,XAML中使用此名称。
ValueType:附加属性值的类型
FromType: 类声明所在类的类型引用
defaultPropertyMetadata:在属性初始化时使用的默认值,用于控件在没设置前有默认布局值!

嵌套控件结构 图3

嵌套控件结构 图3

示例代码:

大概Canvas的重写:

public class Canvas:Panel{public static readonly DependencyProperty TopProperty=DependencyProperty.RegisterAttached(“Top”,typeof(int),typeof(Canvas),new PropertyMetadata(0));

public static readonly DependencyProperty LeftProperty=DependencyProperty.RegisterAttached(“Left”,typeof(int),typeof(Canvas),new PropertyMetadata(0));

//…其它属性

[TypeConverter("System.Windows.LengthConverter, PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, Custom=null")]

[AttachedPropertyBrowsableForChildren]

public static double GetTop(UIElement element){
return element.GetValue(TopProperty);
}

public static void SetTop(UIElement element, double length){
element.SetValue(TopProperty,length);
}
//…其它Set和Get方法,以此类推。。。
}

XAML中:

<Window x:Class=”XamlPad.Window1″
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml
Title=”Window1″ Height=”335″ Width=”348″ Padding=”0″ Margin=”0″>
<Canvas Width=”338″ Height=”308″ x:Name=”Canvas1″>
<Button Canvas.Left=”30″ Canvas.Top=”51″ Height=”69″ Name=”button1″ Width=”131″>Button</Button>
<Button Canvas.Left=”179″ Canvas.Top=”51″ Height=”69″ Name=”button2″ Width=”131″>Button</Button>
<Button Canvas.Left=”30″ Canvas.Top=”134″ Height=”69″ Name=”button3″ Width=”131″>Button</Button>
<Button Canvas.Left=”179″ Canvas.Top=”134″ Height=”69″ Name=”button4″ Width=”131″>Button</Button>
<Button Canvas.Left=”30″ Canvas.Top=”216″ Height=”69″ Name=”button5″ Width=”131″>Button</Button>
<Button Canvas.Left=”179″ Canvas.Top=”216″ Height=”69″ Name=”button6″ Width=”131″>Button</Button>
<Label Canvas.Left=”91″ Canvas.Top=”9″ Height=”32″ Name=”label1″ Width=”142″>Parent Canvas Control</Label>
</Canvas>
</Window>

集合类型属性元素语法

这里指的集合类包括ICollection,IList,IDictionary等.Net标准集合接口实现的类,并用“元素属性”表达。在“元素属性”中添加类型标记,其XAML处理器会自动创建实例并使用Add方法添加入集合属性中。

<Style x:Key=”btnStyle” TargetType=”Button”>
<Style.Setters>
<Setter Property=”Foreground” Value=”Blue”/>
<Setter Property=”Background” Value=”AliceBlue”/>
</Style.Setters>
</Style>

图4
图4中<Style.Setters>为集合属性,两个Setter标记表示Setters中的两个对象!
附加事件

其实附加事件和附加属性是相似的,只不过子控件继承了父控件的事件。WPF一些控件默认也使用了事件冒泡机制,在一个Button中Click事件没有取消向中冒时,会检测父控件是否绑定了ButtonBase.Click的附加事件,如果绑定则执行!一直到最顶层控件。

示例代码:

<Window x:Class=”XamlPad.Window1″
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml
Title=”Window1″ Height=”282″ Width=”283″ Padding=”0″ Margin=”0″>
<Canvas Width=”260″ Height=”246″ x:Name=”Canvas1″ ButtonBase.Click=”BTNCLICK”>
<Button Canvas.Left=”13″ Canvas.Top=”20″ Height=”64″ Name=”button1″ Width=”220″>按扭1</Button>
<Button Canvas.Left=”13″ Canvas.Top=”90″ Height=”64″ Name=”button2″ Width=”220″>按扭2</Button>
</Canvas>
</Window>

程序代码:

private void BTNCLICK(object sender, RoutedEventArgs e)
{
MessageBox.Show((e.Source as Button).Content.ToString());
}

标记扩展

在TyperConverter这之前由XAML处理器调用MarkupExtension抽象类实现,可以通过绑定、资源表达式获取对象赋于属性。表达式的语法格式使用两个大括号包括指令,比如{Binding …}。

<Button Style=”{StaticResource MyStyle}”>My button</Button>

在这里,StaticResource 用来标识 StaticResourceExtension 类,该类提供标记扩展实现。下一个字符串 MyStyle 用作非默认 StaticResourceExtension 构造函数的输入,在该构造函数中,从扩展字符串提取的参数用来声明所请求的 ResourceKey。MyStyle 应当是定义为资源的 Style 的 x:Key 属性 值。StaticResource 标记扩展用法要求使用该资源,在加载时通过静态资源查找逻辑来提供 Style 属性值。

Silverlight之Javascript编程入门

Silverlight的界面是通过控件套用控件来改变页面的布局与实现体验者的视觉效果的。本文介绍Silverlight即时显示JavaScript程序的状态,由灵为详细介绍JavaScript实现对Silverlight的控件访问、修改、删除、创建。

实现效果如下:

提示:对控件进行操作,如果在控件的onLoad之前访问和操作都会出现异常!,是因为找不到对象。
下面的实例是JavaScript循环创建动画的效果,显示内容可以随意改变。控件的格式是XAML中定义的TextBlock(文本控件),包括Animation创建,添加,和删除等功能。
变量说明:

var txtFormat=new _textBlock(); //字体格式对象
var writeText=”Welcom to WPF.COM!”; //运画显示内容
var CanvasLeft=0; //随环改变
var CanvasTop=0; //加载的XAML中的高度位置
var charIndex=0; //显示的字符索引
var split_width=15; //每一个字符的宽度,可以对此智能改变
var _silverlight_c; //指定的Silverlight控件对象
在Page.xaml.js文件中创建了_textBlock类,使用此类记录textBlock中的格式,大小信息。
function _textBlock()
{
this.fontFamily=”";
this.width=0;
this.height=0;
this.textWrapping=”Wrap”;
this.fontSize=0.0;
}

var txtFormat=new _textBlock();
在onLoad事件中加载了XAML中的格式,并把样式控件删除,并且调用了显示动画的方法(goAnimation)。

handleLoad: function(control, userContext, rootElement)
{
this.control = control;
_silverlight_c=control;
var tStyle=control.content.findName(“tStyle”);
for(var i in txtFormat)
{
txtFormat[i]=tStyle[i];
}
CanvasLeft=tStyle["Canvas.Left"];
CanvasTop=tStyle["Canvas.Top"];
control.content.root.children.remove(tStyle);
tStyle=null;
goAnimation();
}

下面是goAnimation的代码:

function goAnimation(){
if(charIndex<writeText.length)
{
var this_char=writeText.substr(charIndex,1);
if(this_char!=” “)
{
var t_control=_silverlight_c.content.createFromXaml(‘<TextBlock xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml” Text=”Hello” x:Name=”t’+charIndex+’”><TextBlock.RenderTransform><TransformGroup><ScaleTransform ScaleX=”1″ ScaleY=”1″/><SkewTransform AngleX=”0″ AngleY=”0″/><RotateTransform Angle=”0″/><TranslateTransform X=”0″ Y=”0″/></TransformGroup></TextBlock.RenderTransform></TextBlock>’);
CanvasLeft+=split_width;
for(var i in txtFormat){t_control[i]=txtFormat[i];}
t_control["Canvas.Top"]=-20;
t_control["Canvas.Left"]=CanvasLeft;
t_control.foreground=”#ffffffff”;
t_control.Text=this_char;
_silverlight_c.content.root.children.add(t_control);
var storyboard_str=’<Storyboard xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml” x:Name=”animation’+charIndex+’”>’;
storyboard_str+=’<DoubleAnimationUsingKeyFrames BeginTime=”00:00:00″ Storyboard.TargetName=”t’+charIndex+’” Storyboard.TargetProperty=”(UIElement.RenderTransform).(TransformGroup.Children)[2].(RotateTransform.Angle)”>’;
storyboard_str+=’<SplineDoubleKeyFrame KeySpline=”0.091,0.532,1,1″ KeyTime=”00:00:00.6000000″ Value=”-360″/>’;
storyboard_str+=”</DoubleAnimationUsingKeyFrames>”;
storyboard_str+=’<DoubleAnimationUsingKeyFrames BeginTime=”00:00:00″ Storyboard.TargetName=”t’+charIndex+’” Storyboard.TargetProperty=”(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)”>’;
storyboard_str+=’<SplineDoubleKeyFrame KeySpline=”0.091,0.532,1,1″ KeyTime=”00:00:00.6000000″ Value=”‘+CanvasTop+’”/>’;
storyboard_str+=’</DoubleAnimationUsingKeyFrames>’;
storyboard_str+=’<DoubleAnimationUsingKeyFrames BeginTime=”00:00:00″ Storyboard.TargetName=”t’+charIndex+’” Storyboard.TargetProperty=”(UIElement.Opacity)”>’;
storyboard_str+=’<SplineDoubleKeyFrame KeyTime=”00:00:00″ Value=”0.055″/>’;
storyboard_str+=’<SplineDoubleKeyFrame KeyTime=”00:00:00.6000000″ Value=”1″/>’;
storyboard_str+=’</DoubleAnimationUsingKeyFrames>’;
storyboard_str+=”</Storyboard>”;
var storyboard_control=_silverlight_c.content.createFromXaml(storyboard_str);
t_control.Resources.add(storyboard_control);
storyboard_control.begin();
}
CanvasLeft+=split_width;
charIndex++;
setTimeout(“goAnimation()”,100);
}
}

使用content.createFromXaml方法创建Silverlight中的对象。
使用content.findName 利用x:Name查找名称对象
使用silverlight_control.children.add添加控件。
使用silverlight_control.Resources.add添加StoryBoard动画对象(Storyboard)。
storyboard_obj.Begin播放。

Silverlight中C#与Javascript事件交互

在本章里,由灵会为您介绍Silverlight的事件相关知识和实例。Silverlight使用了事件冒泡的机制,和Web中的JavaScript事件是一样!每一个控件都可以有自己独有的事件,本文会为大家介绍常用控件的事件。

先简单介绍下事件冒泡机制,理解的朋友要以先跳过此节。Silverlight是使用控件套用控件实现的,比如一个button必须在Canvas容器控件内,所以在点击Button的时候,如果Canvas指定了MouseLeftButtonDown事件,会先执行Button的MouseLeftButtonDown事件,随后执行Canvas的MouseLeftButtonDown事件。
常规事件的绑定有三种方法可以实现,在此为大家介绍。

1、在XAML的控件标记中添加属性制定,以属性=”事件的执行名称”。

<Canvas onLeftButtonDown=”leftButtonDown”></Canvas>

2、使用JavaScript的指定。。

_silverlight_control.content.findName(“controlName”).addEventListener(“onLeftButtonDown”,functionName);

3、使用MSIL的DLL中绑定(只限于Silverlight1.1以上版本)。。

silverlight_control.MouseLeftButtonDown += new System.Windows.Input.MouseEventHandler(silverlight_control_MouseLeftButtonDown);

您可以自定义事件方法,如果想在JavaScript中使用.cs或.vb中声明托管事件,必须要使用[ScriptableType]和[ScriptableMember]标记声明。

下面我们列出常用的事件列表:
事件名称 所在控件 说明。

事件名称 所在控件 说明
Loaded UIElement基类 子控件加载后发生
OnResize System.Windows.Interop.BrowserHost 静态方法,大小重设是发生
OnFullScreenChange System.Windows.Interop.BrowserHost 静态方法,全屏改变时发生
MouseLeftButtonDown UIElement基类 鼠标点击发生
MouseLeftButtonUp UIElement基类 鼠标放开时发生
MouseLeave UIElement基类 鼠标移开时发生
MouseEnter UIElement基类 鼠标经过时发生
DownloadProgressChanged Image, Downloader, MediaElement 进度更改时发生
GotFocus UIElement基类 获得焦点时发生
LostFocus UIElement基类 失去焦点时发生
ImageFailed Image 图像失败时发生
BufferingProgressChanged MediaElement 缓冲更改时发生
CurrentStateChanged MediaElement 播放状态更改时发生
MediaEnded MediaElement 播放停止时发生
MediaFailed MediaElement 播放失败时发生
MediaOpened MediaElementss 打开以后发生
KeyDown UIElement基类 键盘按下时发生
KeyUp UIElement基类 键盘起来时发生
Completed Storyboard 播放完时发生

实例:

C#

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 main_app_wpfhome
{
[ScriptableType]
public partial class Page : UserControl
{
public Page()
{
// Required to initialize variables
InitializeComponent();
this.Loaded += this.Page_Loaded;
}
private void Page_Loaded(object sender, EventArgs args)
{
// Required to initialize variables. Needs to be done from loaded event so FindName works properly.
System.Windows.Browser.HtmlPage.RegisterScriptableObject(“Page”, this);
Storyboard1.Completed += new EventHandler(Storyboard1_Completed);
// Insert code required on object creation below this point.
}

void Storyboard1_Completed(object sender, EventArgs e)
{
if (Finish != null)
{
Finish(sender, e);
}
}
[ScriptableMember]
public event EventHandler Finish;
}
}

其中System.Windows.Browser.HtmlPage.RegisterScriptableObject(“Page”, this);是把自身在JavaScript声明,让Javascript所调用!这一步是非常重要的,但是其中this对象必须使用[ScriptableType]标识声明才可以。下面JavaScript片段实现了对象的调用。
JavaScript代码段:

var silverlightControl;
function sl_load(sender,arg)
{
silverlightControl=document.getElementById(‘Silverlight1′);
silverlightControl.content.Page.Finish=window.finish_handler;
silverlightControl.content.root.addEventListener(“MouseLeftButtonDown”,rePlay);
}
function finish_handler(sender,arg)
{
document.getElementById(‘RePlay’).style.display=’inline’;
}
function rePlay()
{
var cc=silverlightControl.content.findName(“Storyboard1″);
cc.Stop();
cc.begin();
document.getElementById(‘RePlay’).style.display=’none’;
}

本实例是一个事件交互的程序,首选用Blend在Xaml中制做出一个动画Storyboard的实例对象。使用程序声明事件,并用Javascript调用事件委托。虽然可以在JavaScript中直接使用Storyboard. Completed实现,但在此实现JavaScript与C#事件托管实现!

ScrollViewer控件实现拖拽和缩放

Silverlight从1.0版本一直支持对鼠标的施动,这个实例使用了Silverlight2.0开发。并在拖动过程中实现了加速算法,和缩放功能。一些基本知识由灵在此不做详细介绍了,需要的请结合本教程中的基础知识做本文实例。

浏览效果:

打开Expression Blend 2.5,新建一个Silverlight 2 Application项目,并在page.xaml中施放添加页面所需的控件:
TextBlock(文本显示控件),命名为percent,然后以可以把内容输入“0%”为了让设计人员在设计中直接看到效果。
TextBlock(文本显示控件),内容输入为“缩放”,说明Slider控件的功能。
Slider(滑块控件),Maximum属性为“1000”,Minimum为“0”,值为“100”,Orientation为“Horizontal”。
ScrollViewer(滚动控件)HorizontalScrollBarVisibility设为Hidden,VerticalScrollBarVisibility设为Hidden。用于定位其子控件的视图位置,并添加子控件:
Image(图像控件),Source属性中制定显示的图像,Stretch设为Uniform,让图像不变形。并把Cursor属性设为Hand,命名为“img_c”。
如图所示:
ScrollViewer控件实现拖拽和缩放
图1.0

在Project项目面板中选中项目名称,右键菜单中点击“Edit Visual Studio”进入Visual Studio添加程序代码(如果VisualStudio中无法可视化编辑请到“最新Silverlight开发环境配置介绍”搭建开发环境吧)!

主要使用代码功能:

UIElement.CaptureMouse(); 启用鼠标拖动事件(就算鼠标离开窗体后放开鼠标也调用MouseLeftButtonUp和MouseMove事件)

UIElement.ReleaseMouseCapture(); 释放UIElement.CaptureMouse的鼠标拖动。

MouseEventArgs.GetPosition    获取事件当前鼠标的相对坐标位置。

Image.Stretch  Image图像控件的显示方式,None为不缩放,Fill按控件的Width和Height而缩放变化,Uniform则按实际图像比例大小缩放,UniformToFill是按照图原大小比例,以最大的填充Image显示。

Image.ActualHeight Image的希望大小,Image.Stretch为None时,Image的大小为显示的图片实际大小!

Slider.Value 为获取Slider控件的滑块当前值置的值。

ScrollViewer.ScrollToVerticalOffset 设置ScrollViewer控件的垂直滚动条的位置。

ScrollViewer.ScrollToHorizontalOffset 设置ScrollViewer控件的水平滚动条的位置。

现在为Silverlight的Image控件和Slider控件添加事件:

Slider.ValueChanged=”Slider_ValueChanged”

Image.MouseLeftButtonDown=”Image_MouseLeftButtonDown” MouseLeftButtonUp=”Image_MouseLeftButtonUp”

代码:

namespace album
{
public partial class main : UserControl
{
MouseEventHandler meh;
double img_actualWidth = 0;
double img_actualHeight = 0;
public main()
{
// Required to initialize variables
meh = new MouseEventHandler(img_c_MouseMove);
InitializeComponent();
}
Point MouseDownAt;
private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
img_c.MouseMove += meh;
MouseDownAt = e.GetPosition(null);
img_c.CaptureMouse();
}

void img_c_MouseMove(object sender, MouseEventArgs e)
{
Point p=e.GetPosition(null);
img_Scroll.ScrollToVerticalOffset(img_Scroll.VerticalOffset – ((p.Y – MouseDownAt.Y) * 1.2));
img_Scroll.ScrollToHorizontalOffset(img_Scroll.HorizontalOffset -(( p.X – MouseDownAt.X)*1.2));
MouseDownAt = p;
//img_c.SetValue(image.LeftProperty, p.X – MouseDownAt.X);
//img_c.SetValue(Canvas.TopProperty, p.Y – MouseDownAt.Y);
//img_translate.X = p.X – MouseDownAt.X;
//img_translate.Y = p.Y – MouseDownAt.Y;
//img_c.SetValue(Canvas.LeftProperty, p.X – MouseDownAt.X);
//img_c.SetValue(Canvas.TopProperty, p.Y – MouseDownAt.Y);
}

private void Image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
img_c.MouseMove -= meh;
img_c.ReleaseMouseCapture();
}

private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs e)
{
if (img_scale != null)
{
string t = e.NewValue.ToString();

img_c.Width = (zoom_slider.Value/100) * img_actualWidth;
img_c.Height = (zoom_slider.Value/100) * img_actualHeight;

string leftT = “”;
string rightT = “”;
int index=t.IndexOf(‘.’);
if (index != -1)
{
leftT = t.Substring(0, index);
rightT = t.Substring(index + 1, t.Length – index – 1);
if (rightT.Length > 1)
{
rightT = rightT.Substring(0, 1);
}
}
else
{
leftT = t;
rightT = “0″;
}
if (leftT.Length == 1)
leftT = “0″ + leftT;
percent.Text = leftT+”.”+rightT+ “%”;
//img_scale.ScaleX = e.NewValue;
//img_scale.ScaleY = e.NewValue;
}
//betwenText.Text = “df”;
}
private void img_c_Loaded(object sender, RoutedEventArgs e)
{
percent.Text = “100%”;
zoom_slider.Value = 100;
Stretch s = img_c.Stretch;
img_c.Stretch = Stretch.UniformToFillUniform;
img_actualHeight = img_c.ActualHeight;
img_actualWidth = img_c.ActualWidth;
img_c.Stretch = s;
//img_c.Width = img_c.DataContext;
//img_c.Height = img_c.DesiredSize.Height;
}
}
}

Javascript实现Silverlight右键菜单

本篇主要讲述了Silverlight中右键菜单的实现方法,希望对您有所帮助!

由灵(作者)使用的是Expression Blend 2.5 March 2008 Preview版本开发,其中使用的“Silverlight 1 Site”项目。并没有涉及到2.0技术,本实例使用JavaScript作为交互语言!其中主要使用HTML中控件的oncontextmenu事件屏蔽Silverlight插件的右键菜单,并且调用XAML中的菜单显示(动画)或隐藏。

效果:

打开Silverlight 1 Site项目的默认添加文件“Page.xaml”文件。在可视化视图中创建一个动画,并且命名为“animation”,这个动画是由您随意设的,菜单将会控制这个animation的播放与暂停。

最后设计菜单项,其中包括“播放”、“暂停”两个按扭,这些MouseEnter和MouseLeave和MouseLeftButtonDown等事件您可以随意设定!并助把这两个按扭进行自定义,并且合组后命名为“menu”。然后为这个Menu组合设计弹出和隐藏时的运画,显示是命名为“show_menu”,“hidden_menu”,最后把context的Opacity(透明度)设为零(请注意:在显示菜单的动画中请把Opacity值显示出来)!

如图:
javascript实现Silverlight右键菜单

现在我们要用动画的组件都制作好了,然后由脚本代码联起来!

这一步是必须的,在createSilverlight的初始化参数isWindowless为’true’。这样就可以使用Silverlight插件的oncontextmenu事件了!如果您不明白这步,请下载实例后打开default.html查找“isWindowless”就可以找到。

主要脚本(page.xaml.js)片段:

control.oncontextmenu=Silverlight.createDelegate(this,function(s,e){
this.showMenu(event);
return false;
});

这是在Silverlight插件的加载事件中绑定的oncontextmenu事件,使用return false取消的Silverlight默认菜单,并且使用this.showMenu显示菜单:

showMenu:function(e)
{
var p=mousePosition(e);
p.x-=this.control.offsetLeft;
p.y-=this.control.offsetTop;
if(p.x+this.control.content.findName(“menu”).width>this.control.content.root.width)
{
p.x=this.control.content.root.width-this.control.content.findName(“menu”).width;
}
if(p.y+this.control.content.findName(“menu”).height>this.control.content.root.height)
{
p.y=this.control.content.root.height-this.control.content.findName(“menu”).height;
}
this.control.content.findName(“menu”)["Canvas.Left"]=p.x;
this.control.content.findName(“menu”)["Canvas.Top"]=p.y;
this.control.content.findName(“show_menu”).begin();
this.isMenu=true;
}

function mousePosition(ev){
if(ev.pageX || ev.pageY){
return {x:ev.pageX, y:ev.pageY};
}
return {x:ev.clientX + document.body.scrollLeft – document.body.clientLeft, y:ev.clientY + document.body.scrollTop – document.body.clientTop};
}

其中mousePosition获取的页面中鼠标的坐标位置,并且计算为Silverlight插件中的坐标位置。并把菜单的位置赋给menu的坐标,并显示出来!

C#实现Silverlight中右键菜单

在flash中 其提供了一个可定制话的右键菜单系统.(ContextMenu)

这个在silverlight中也是一样可以做到的。

过程如下:

1.添加一个<TextBlock>到Page.xaml中

<UserControl x:Class=”rightClick.Page”
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
Width=”400″ Height=”300″>
<Grid x:Name=”LayoutRoot” Background=”White”>
<TextBlock x:Name=”MyField”>Right click please.</TextBlock>
</Grid>
</UserControl>

2.在页面中设置silverlight的参数Windowless=”true”

<asp:Silverlight ID=”Silverlight1″ runat=”server” Height=”480px”
MinimumVersion=”2.0.30523″ Source=”~/ClientBin/rightClick.xap”
Windowless=”true” Width=”640px” />
<object data=”data:application/x-silverlight,” type=”application/x-silverlight-2-b2″ width=”100%” height=”100%”>
<param name=”source” value=”ClientBin/rightClick.xap”/>
<param name=”onerror” value=”onSilverlightError” />
<param name=”background” value=”white” />
<param name=”Windowless” value=”true” />
<a href=”http://go.microsoft.com/fwlink/?LinkID=115261″ style=”text-decoration: none;”>
<img src=”http://go.microsoft.com/fwlink/?LinkId=108181″ alt=”Get Microsoft Silverlight” style=”border-style: none”/>
</a>
</object>

3.最后修改Page.xaml.cs页面的代码

新建立一个ContextMenuInterceptor类.这个类是用来处理页面中“OnContextMenu”事件的.在用到HTMLPage对象你需要引入System.Window.Browser命名空间.

在调用e.PeventDefault()方法后,将会取消右键点击事件.所以silverlight不会捕捉到它.

在这里我们已经成功的拦截了右键点击事件,做我们想做的任何事情了.;)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Browser;

namespace rightClick
{
public partial class Page : UserControl
{
ContextMenuInterceptor _cmi = null;
public Page()
{
InitializeComponent();
_cmi = new ContextMenuInterceptor(MyField);
}

}

public class ContextMenuInterceptor
{
TextBlock TextField;

public ContextMenuInterceptor(TextBlock textField)
{
TextField = textField;
HtmlPage.Document.AttachEvent(“oncontextmenu”, this.OnContextMenu);
}

private void OnContextMenu(object sender, HtmlEventArgs e)
{
TextField.Text = “Right Clicked Blocked at ” + e.OffsetX + “,” + e.OffsetY;

//Cancels the event if it is cancelable.
e.PreventDefault();
}
}
}

Silverlight 本地资源“文件”

什么是本地资源

Silverlight 资源
图1

资源文件包含在Silverlight应用程序的项目窗口(图1所示)中,在项目生成后打包在.xap文件中,使Silverlight应用程序加载。使用菜单:“窗口 > 项目”显示隐藏项目窗口,这里1150810574.jpg是用户添加进去的资源文件。

添加资源文件

Silverlight 添加资源文件
图2

在资Windows 资源管理器中找到要添加的图片或文本等资源文件,右键菜单中复制文件到“剪切板”中,如图2中所示。转到Expression Blend中后,在项目窗口中的项目图标上右键菜单,选择“在Visual Studio 中编辑”,如图3所示。

Silverlight 添加资源文件 图3
图3

这时会打开Visual Studio2008,进入代码编写模式。

打开“Solution Explorer(解决方案 资源管理器)”窗口项目右键菜单中选择“Paste(粘贴)”如图4中所示。

Silverlight 添加资源文件 图4
图4

这时,在Windows资源管理器中复制的文件添加到Silverlight项目中,选择文件,属性窗口中“BuildAction(编译方式)”选为“Resource(资源)”。

使用程序代码加载图片

读取资源的方法:Application.GetResourceStream(Uri uri): StreamResourceInfo

Page.xaml文件

<UserControl

xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”

xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”

x:Class=”SilverlightApplication7.Page”

Width=”640″ Height=”480″>

<Grid x:Name=”LayoutRoot” Background=”White”>

</Grid>

</UserControl>

Page.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.Resources;

using System.Windows.Media.Imaging;

namespace SilverlightApplication7

{

public partial class Page : UserControl

{

public Page()

{

// 需要初始化变量

InitializeComponent();

this.MouseLeftButtonDown += new MouseButtonEventHandler(Page_MouseLeftButtonDown);

}

void Page_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)

{

Image img = LoadImage(“/SilverlightApplication7;component/1150810574.jpg”);

LayoutRoot.Children.Add(img);

}

Image LoadImage(string relativeUrlString)

{

Uri uri = new Uri(relativeUrlString, UriKind.Relative);

StreamResourceInfo sri = Application.GetResourceStream(uri);

BitmapImage bimg = new BitmapImage();

bimg.SetSource(sri.Stream);

Image img = new Image();

img.Source = bimg;

return img;

}

}

}

使用代码加载文本

Uri uri = new Uri(“/SilverlightApplication7;component/remark.txt”, UriKind.Relative);

StreamResourceInfo sri = Application.GetResourceStream(uri);

System.IO.StreamReader reader = new System.IO.StreamReader(sri.Stream);

MessageBox.Show(reader.ReadToEnd());

Bookmark and Share

喜欢这篇文章的人还喜欢。。。

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Comment