在前两篇文章中,我们已经创建了“放大镜效果”和“放大镜CheckBox”,本篇内容将通过CheckBox来控制放大镜效果的开/关状态,并完成全部“放大镜”功能。在进行本篇内容前请确保您已经阅读过:
在完成本篇内容后将实现以下效果:
1. 下载BaseBehavior.zip 进入VS 将以下程序加入到Interactivity 文件夹(参考资料 Base Classes for Custom Behaviors)
· BaseBehavior.cs
· BaseBehaviorT.cs
2. 下载SetInteractionPropertyAction.zip 新增Interactivity\SetInteractionPropertyAction 文件夹,并将以下程序加入其中(参考资料 Creating an Action to set Properties on Actions & Behaviors)
· ConverterHelper.cs
· SetInteractionPropertyAction.cs
添加完以上四个程序,注意其命名空间应为:FindObject。
其中,ConverterHelper.cs 和SetInteractionPropertyAction.cs 程序需要使用CodePlex 的Expression Blend Samples 项目,下载安装后将Expression.Samples.Interactivity、Expression.Samples.Shaders 加入Reference:
3. 打开MagnifierOverBehavior.cs 要使MagnifierOverBehavior 继承BaseBehavior 类,以此来使用IsEnabled 属性。将Behavior 改为BaseBehavior:
public class MagnifierOverBehavior : BaseBehavior<FrameworkElement>
将AssociatedObject_MouseEnter 默认显示放大镜注释掉,需要通过IsEnabled 来进行调用:
private void AssociatedObject_MouseEnter( object sender, MouseEventArgs e ) { this.AssociatedObject.MouseMove +=
new MouseEventHandler( AssociatedObject_MouseMove ); //this.AssociatedObject.Effect = this.magnifier; }
AssociatedObject_MouseMove 也要通过IsEnabled 来判断是否开启放大镜功能:
private void AssociatedObject_MouseMove( object sender, MouseEventArgs e ) { if (IsEnabled) { if (this.AssociatedObject.Effect != this.magnifier) { this.AssociatedObject.Effect = this.magnifier; } (this.AssociatedObject.Effect as Magnifier).Center = e.GetPosition(this.AssociatedObject); Point mousePosition = e.GetPosition(this.AssociatedObject); mousePosition.X /= this.AssociatedObject.ActualWidth; mousePosition.Y /= this.AssociatedObject.ActualHeight; this.magnifier.Center = mousePosition; Storyboard zoomInStoryboard = new Storyboard(); DoubleAnimation zoomInAnimation = new DoubleAnimation(); zoomInAnimation.To = this.magnifier.Magnification; zoomInAnimation.Duration = TimeSpan.FromSeconds(0.5); Storyboard.SetTarget(zoomInAnimation, this.AssociatedObject.Effect); Storyboard.SetTargetProperty(zoomInAnimation,
new PropertyPath(Magnifier.MagnificationProperty)); zoomInAnimation.FillBehavior = FillBehavior.HoldEnd; zoomInStoryboard.Children.Add(zoomInAnimation); zoomInStoryboard.Begin(); } }
4. 回到Blend,在TreeView 中打开magnifierCanvas 选择MagnifierOverBehavior 将其命名为magnifierBehavior,并将IsEnabled 属性设为false:
5. 在Assets->Behaviors 中为CheckBox 添加两个SetInteractionPropertyAction:
6. 第一个SetInteractionPropertyAction 用于启动放大镜功能,进行如下设置:
· EventName: Checked
· TargetName: magnifierCanvas
· ObjectName: magnifierBehavior
· PropertyName: IsEnabled
· Value: true
7. 第二个SetInteractionPropertyAction 用于关闭放大镜功能,进行如下设置:
· EventName: Unchecked
· TargetName: magnifierCanvas
· ObjectName: magnifierBehavior
· PropertyName: IsEnabled
· Value: false
8. 确定CheckBox 的IsChecked 属性是false 状态,运行程序便可实现放大镜可控效果。
9. 最后在放大镜下面加一个Notepad 图片,使其更加美观:
源代码下载:
本文转自Gnie博客园博客,原文链接:http://www.cnblogs.com/gnielee/archive/2010/01/05/silverlight-puzzle-game-part7.html,如需转载请自行联系原作者