基于Cairngorm的Silverlight开发 - part2

本文介绍如何在Cairngorm框架下利用ModelLocator实现数据绑定,通过一个控制矩形宽度的例子展示了ModelLocator的基本用法及其实现过程。

 

搭建架构

 

由浅入深的来搭建架构。

从ModelLocator开始
ModelLocator只是Cairngorm中的一个部分,要使用它并不一定要把Cairngorm所有的架构都搭建起来,ModelLocator是可以单独来使用的。

ModelLocator是Silverlight程序中的一个数据的容器,所有的数据都存在于一个类中"singleton class"。这个类有且仅有一个实例。他使用的是设计模式中的 单件模式。(这里我也不多说了,李老师已经 说的很清楚了。ModelLocator,简约而不简单)

这里举例来说明一下ModelLocator具体的用法。一个最简单的例子,我想通过Silverlight中的Slider控件来控制一个矩形Rectangle的Width属性。

首先建立Silverlight项目并在项目网站上获取Cairngorm,添加对其的引用。在项目中新建立文件夹Model用来存放ModelLocator模型,建立MyModelLocator类并继承自ModelLocator,套用单件模式,并声明一个属性。


    
public   class  MyModelLocator : ModelLocator
    {
        
private   static   readonly  MyModelLocator _instance  =   new  MyModelLocator();

        
public   static  MyModelLocator Instance {  get  {  return  _instance; } }

        
static  MyModelLocator(){}
        
private  MyModelLocator()
            : 
base (){}

        
private   double  _width  =   200 ;
        
public   double  width
        {
            
get  {  return  _width; }
            
set
            {
                _width 
=  value;
                NotifyPropertyChanged(
" width " );
            }
        }
    }

 


切换到Blend工具添加两个控件:Rectangle、Slider。并起好实例名称。换回到Vs工具,指定当前的page页面包含的数据为刚刚建立的MyModelLocator类,对两个控件进行数据双向绑定,绑定Rectangle的WidthProperty属性和Slider的ValueProperty属性到MyModelLocator的width属性上。

     public   partial   class  Page : UserControl
    {
        
public  Page()
        {
            InitializeComponent();

            
this .Loaded  +=   new  RoutedEventHandler(Page_Loaded);
        }

        
void  Page_Loaded( object  sender, RoutedEventArgs e)
        {
            
this .DataContext  =  MyModelLocator.Instance;
            Binding bindwidth 
=   new  Binding( " width " );
            bindwidth.Mode 
=  BindingMode.TwoWay;
            xRectangle.SetBinding(UserControl.WidthProperty, bindwidth);

            xSlider.SetBinding(Slider.ValueProperty, bindwidth);
        }
    }

 

说了一堆理论上的东西还是送上视频直接些。  :)

 

 

基于Cairngorm的Silverlight开发 - part1

转载于:https://www.cnblogs.com/nasa/archive/2009/03/12/Cairngorm-Silverligh-part2.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值