现在的位置: 首页 > 综合 > 正文

一步一步学Silverlight 2系列(35):升级Silverlight 2 Beta 1应用程序到Beta 2

2011年01月30日 ⁄ 综合 ⁄ 共 11041字 ⁄ 字号 评论关闭
文章目录

摘要

Silverlight 2 Beta 2发布之后,在原来的Beta 1基础之上有了很多的改变。本文总结一下Silverlight 2 Beta1 和Beta 2之间的变化,以及升级Silverlight 2.0 Beta 1应用程序到Beta 2过程中可能会遇到的一些问题。

1.卸载原有的与Beta 1有关的一切组件

2.安装Beta 2相关组件

3.在打开原有的项目后,会出现如下提示对话框,提示你是否要升级到最近版本。

控件变化

控件放在System.Windows.dll程序集中

原来在System.Windows.Controls.dll中的控件在Beta 2中都放在了System.Windows.dll中,这意味着这些控件都已经在Runtime中。如果在原来的程序中有如下代码,需要移除:

xmlns:my="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"

并且需要修改对应命名空间下的控件声明,如:

<my:Button x:Name="myButton"/>

在Beta 2中,经过这样的调整之后,可以极大的减小xap文件的体积。

Tooltip的变化

在Silverlight Beta 2中已经不允许直接使用Tooltip了,只能通过ToolTipService来使用,另外移除了ToolTipService中的下面一些公有属性和方法:

BetweenShowDelayProperty

InitialShowDelayProperty

ShowDurationProperty

GetBetweenShowDelay

GetInitialShowDelay

GetShowDuration

SetBetweenShowDelay

SetInitialShowDelay

GetToolTip

SetShowDuration

Beta 1中的ToolTipService实现大家可以参考Silverlight 2 Beta 1控件源代码。现在修改后的ToolTipService公开的API非常简单,如下代码所示:

public static class ToolTipService
{
    public static readonly DependencyProperty ToolTipProperty;
    public static void SetToolTip(DependencyObject element, object value);
}

对于如何使用ToolTipService如下代码所示:

<Button ToolTipService.ToolTip="This is ToolTip text"/>
<Button Content="Button">
    <ToolTipService.ToolTip>
        <TextBlock Text="text"/>
  </ToolTipService.ToolTip>
</Button>

或者

ToolTipService.SetToolTip(myElementNeedingAToolTip, new TextBox());

从控件中移除字体属性

在Beta 2中,字体属性都放在了Control基类中,所以如果你在自定义控件时定义了自己的字体属性,需要进行修改,这些属性包括:

FontFamily

FontSize

FontWeight

FontStyle

Foreground

FontStretch

现在如果在父元素中定义了它们,子元素将会自动继承这些属性,如:

<UserControl x:Class="TerryLee.SilverlightBeta2Example.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="400" Height="300"
    FontSize="16"
    FontFamily="Trebuchet MS">
    <Grid x:Name="LayoutRoot" Background="White">
        ……
    </Grid>
</UserControl>

DatePicker和Calendar

DatePicker和Calendar控件的变化,如下所示:

Calendar

[Remove] bool AreDatesInPastSelectable

[Remove] Style DayStyle

[Remove] Style MonthStyle

[Remove] DateTime SelectableDateStart

[Remove] DateTime SelectableDateEnd

DatePicker

[Remove] bool AreDatesInPastSelectable

[Remove] DateTime SelectableDateStart

[Remove] DateTime SelectableDateEnd

Calendar和DatePicker

[Remove] bool IsEnabled {get; set;}

[Remove] DateTime DisplayDateStart {get; set;}

[Remove] DateTime DisplayDateEnd {get; set;}

[Add] DateTimeRange DisplayRange {get; set;}

ButtonBase类变化

在Beta 1中,ButtonBase是一个partial类:

public partial class ButtonBase : ContentControl
{
    // ...... 
}

而在Beta 2中,它修改为了一个abstract类:

public abstract class ButtonBase : ContentControl
{
    // ...... 
}

并且移除了internal的成员,这些成员包括:

OnIsEnabledChanged

OnGotFocus

OnIsPressedChanged

IsFocused

IsMouseOver

IsMouseOverProperty

IsFocusedProperty

OnKeyDown

OnKeyUp

OnLostFocus

OnMouseEnter

OnMouseLeave

OnMouseLeftButtonDown

OnMouseLeftButtonUp

OnMouseMove

如果你曾经利用ButtonBase类开发过相关的控件,可能需要做一些修改。

TextBox控件变化

在Beta 2中TextBox控件支持带换行的文本卷动,多行文字选择等功能。这一切,都源于TextBox控件内部模板的改变,Beta 1中TextBox控件模板如下:

<ControlTemplate
  xmlns='http://schemas.microsoft.com/client/2007'
  xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
    <Border x:Name='ELEMENT_Content'"
    BorderThickness='{TemplateBinding BorderThickness}'
    BorderBrush='{TemplateBinding BorderBrush}'
    Background='{TemplateBinding Background}'
    Padding='{TemplateBinding Padding}'/>
</ControlTemplate>

Beta 2中TextBox控件模板

<ControlTemplate
  xmlns='http://schemas.microsoft.com/client/2007'
  xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
    <Grid x:Name='RootElement'>
        <Grid.Resources>
            <SolidColorBrush x:Key='Background' Color='#FF003255'/>

            <SolidColorBrush x:Key='BorderBrush' Color='#FF000000'/>
            <SolidColorBrush x:Key='AccentBrush' Color='#FFFFFFFF'/>

            <LinearGradientBrush x:Key='FocusedStrokeBrush'
        StartPoint='0.5,0' EndPoint='0.5,1'>
                <GradientStop Color='#B2FFFFFF' Offset='0'/>
                <GradientStop Color='#51FFFFFF' Offset='1'/>
                <GradientStop Color='#66FFFFFF' Offset='0.325'/>
                <GradientStop Color='#1EFFFFFF' Offset='0.325'/>
            </LinearGradientBrush>

            <Storyboard x:Key='Normal State'>
                <DoubleAnimation Storyboard.TargetName='FocusVisualElement'
          Storyboard.TargetProperty='Opacity' To='0' Duration='0:0:0.0'/>
            </Storyboard>

            <Storyboard x:Key='Focused State'>
                <DoubleAnimation Storyboard.TargetName='FocusVisualElement'
          Storyboard.TargetProperty='Opacity' To='1' Duration='0:0:0.0'/>
            </Storyboard>
        </Grid.Resources>

        <Rectangle StrokeThickness='.5' RadiusX='2'
      RadiusY='2' Fill='{TemplateBinding Background}'/>

        <Rectangle StrokeThickness='.5' RadiusX='2' RadiusY='2'
      Stroke='#FF003255'/>
        <Border x:Name='ContentElement' Padding='{TemplateBinding Padding}'/>

        <Grid x:Name='FocusVisualElement' Opacity='0' IsHitTestVisible='False'>
            <Rectangle RadiusX='1' RadiusY='1' Margin='2'
        Stroke='{StaticResource AccentBrush}' StrokeThickness='1'/>
            <Rectangle RadiusX='1' RadiusY='1'
        Stroke='{StaticResource Background}' StrokeThickness='2'/>
            <Rectangle RadiusX='1' RadiusY='1'
        Stroke='{StaticResource FocusedStrokeBrush}' StrokeThickness='2'/>
        </Grid>
    </Grid>
</ControlTemplate>

如果你在Beta 1中定义了TextBox的Style,需要进行一些修改,如ELEMENT_Content现在变为了ContentElement。

Image和ImageBrush变化

Beta 2中移除了ExceptionRoutedEventHandler而采用泛型的EventHandler来实现,并且移除了DownloadProgress属性。

Beta 1:

// Image class:
    public event ExceptionRoutedEventHandler ImageFailed;
    public double DownloadProgress { get; set;}

// ImageBrush class:
    public event ExceptionRoutedEventHandler ImageFailed;
    public double DownloadProgress { get; set;}

Beta 2:

// Image class:
    public event EventHandler<ExceptionRoutedEventArgs> ImageFailed;

// ImageBrush class:
    public event EventHandler<ExceptionRoutedEventArgs> ImageFailed;

Control加上了边框属性

在Beta 2中,Control基类提供了两个边框属性BorderBrush和BorderThickness,如果大家在Beta 1中自定义控件时定义了这两个属性,现在需要将其移除,并利用基类提供的属性。

public abstract class Control : FrameworkElement
{
    public Brush BorderBrush { get; set; }
    public Thickness BorderThickness { get; set; }
}

ListBox变化

在Beta 2中,ListBox移除了如下属性和事件:

SelectedItemsProperty

SelectionModeProperty

SelectedItems

SelectionMode

OnGotFocus(RoutedEventArgs)

OnItemContainerStyleChanged(Style, Style)

OnKeyDown(KeyEventArgs)

OnLostFocus(RoutedEventArgs)

OnSelectedItemsChanged(IList, IList)

OnIsSelectionActiveChanged(Boolean, Boolean)

OnSelectedIndexChanged(Int32, Int32)

OnSelectedItemChanged(Object, Object)

OnSelectionChanged(SelectionChangedEventArgs)

OnSelectionModeChanged(SelectionMode, SelectionMode)

对于ListBoxItem移除了如下属性和事件:

OnGotFocus(RoutedEventArgs)

OnLostFocus(RoutedEventArgs)

OnMouseEnter(MouseEventArgs)

OnMouseLeave(MouseEventArgs)

OnMouseLeftButtonDown(MouseButtonEventArgs)

IsMouseOver

同时移除了ListBox的选择模式枚举类SelectionMode,也就意味着在Beta 2中ListBox只能实现单选,除非自行做扩展。其实在Beta 1中SelectionMode也只有一个值Single,Beta 2中的ListBox提供了SelectedItem属性和SelectionChanged事件。

WatermarkedTextBox控件

在Beta 1中加入的控件WatermarkedTextBox控件到了Beta 2中被移除,所以如果你在Beta 1的应用程序中使用了该控件需要用TextBox来替换。不过好在我们已经有了Beta 1中WatermarkedTextBox控件的源码,在Beta 2下重新实现一个也不是一件什么难事。

新的TabControl

在Beta 2中添加了新的TabControl控件,但是该控件放在System.Windows.Controls.Extended程序集中,使用时需要添加命名空间。

DataGrid控件

非常幸运的是如果我们在Beta 1的应用程序中使用了DataGrid控件,变化的地方并不多,而是新增了很多有用的功能。如实现排序等。

扩展控件

程序集System.Windows.Controls.Extended仍然保留,其中包括了四个控件,在使用的时候需要对这些控件导入命名空间。

Calendar

DatePicker

GridSplitter

TabControl

如:

<UserControl 
    xmlns:my="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Extended" 
    x:Class="TerryLee.SilverlightBeta2Example.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="400" Height="300"
    FontSize="16"
    FontFamily="Trebuchet MS">
    <Grid x:Name="LayoutRoot" Background="White">
        <my:DatePicker x:Name="myDatePicker"></my:DatePicker>
        <my:Calendar x:Name="myCalendar"></my:Calendar>
    </Grid>
</UserControl>

Visual State Manager

在Silverlight 2 Beta2中引进的一个新东西是"Visual State Manager(视觉状态管理器)" (VSM),该功能将极大地方便你建造交互性的控件模板。VSM引入了你可在控件模板中利用的2个基本概念:"视觉状态(Visual States)" 和 "状态迁移(State Transitions)"。例如,象按钮这样的控件为自己定义了多个视觉状态: "Normal(正常)", "MouseOver(鼠标之下)", "Pressed(按下)", "Disabled(不可用)", "Focused(获取焦点)", "Unfocused(不具焦点)"。在Blend中的模板编辑模式下,设计师现在可以轻松地编辑按钮在每个特定状态下的外观,以及设置迁移规则来控制从一个状态迁移到另一个状态时动画效果应该运行的时间。然后在运行时,Silverlight会动态地运行合适的动画故事板来把控件从一个状态平滑地过渡到另一个状态。(ScottGu)

网络通信

WCF通信

在Beta 2中,WCF现在支持双工通信服务了,但是仍然只支持basicHttpBinding绑定。这将促成一个非常干净的编程模型,允许服务器将消息“推送”到Silverlight客户端,而不用开发人员手工轮询服务器端的变动。这个编程模型在多种场景中都非常有用,包括即时消息/聊天应用,象股票行情和交易这样的监测/更新应用等。

WebClient和HttpWebRequest

Beta 2中允许使用WebClient上传数据,以及允许我们在后台线程上调用WebClient或者HttpWebRequest,在异常处理上也需要做一些改动。

Beta 1

public void Download()
{
    WebClient client = new WebClient();
    client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(
        client_DownloadStringCompleted);

    try
    {
        client.DownloadStringAsync(new Uri("http://Contoso.com/myfile.txt"));
    }
    catch (SecurityException ex)
    {
        // handle synchronous exception
    }
}

void client_DownloadStringCompleted(
    object sender, DownloadStringCompletedEventArgs e)
{
    // Set the text content of a control to the result
    MyControl.Text = e.Result;
}

Beta 2

public void Download()
{
    WebClient client = new WebClient();
    client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(
        client_DownloadStringCompleted);

    client.DownloadStringAsync(new Uri("http://Contoso.com/myfile.txt"));
}

void client_DownloadStringCompleted(
    object sender, DownloadStringCompletedEventArgs e)
{
    try
    {
        // Set the text content of a control to the result
        MyControl.Text = e.Result;
    }
    catch (SecurityException ex)
    {
        // handle asynchronous exception
    }
}

LINQ to JSON支持

Beta 2中提供了LINQ to JSON的支持,允许你在Silverlight应用中轻松地查询,过滤,并将JSON结果映射到.NET对象上,这方便了对已经发布在网上的现有的AJAX端点和服务的调用和操作。

跨域Sockets

Beta2现在允许跨域的HTTP和Sockets的networking支持(意味着你的应用可以调用不同于当前应用下载自的站点的网站)。

Silverlight会查看目标服务器上是否存在这样的XML策略文件,这文件表明了是否允许跨域网络访问。Silverlight支持一个我们开发的新XML策略文件格式,以及Flash策略文件(意味着可为Flash所用的现有的网站,不用费额外的功夫,就可在Silverlight中调用)。

浏览器集成

HtmlPage变化

Beta 1中HtmlPage提供了UnregisterScriptableObject方法,允许我们取消注册一个可被脚本访问的托管对象,Beta 2中已经移除了该方法,对于取消注册一个可在脚本中创建对象的类型方法UnregisterCreateableType仍然保留。

HtmlElement变化

Beta 1中可以使用HtmlElement.GetProperty和HtmlElement.GetAttribute方法来互相访问HTML DOM的Property或者Attribute,Beta 2已经取消了这一行为,只能使用HtmlElement.GetProperty方法来访问HTML DOM的Propery,而只能使用HtmlElement.GetAttribute来访问HTML DOM的Attribute。

隔离存储

隔离存储空间大小

IsolatedStorage是Beta 1中提供的非常有用的新特性,在Beta 2中存储的大小增加到了1M;

增加空间方法更名

Beta 2中隔离存储请求增加空间的方法名由TryIncreaseQuotaTo()变化为了IncreaseQuotaTo(),微软解释此举是因为该方法虽然加了Try,但仍然没有使用Try Pattern,所以移除比较合适。

Beta 1:

IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
storage.TryIncreaseQuotaTo(maxSize);

Beta 2:

IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
storage.IncreaseQuotaTo(maxSize);

新增按Site存储

在Beta 1下隔离存储只能按照应用程序存储,Beta 2中增加按照站点存储:

Beta 2:

IsolatedStorageFile storage;
storage = IsolatedStorageFile.GetUserStoreForApplication();
storage = IsolatedStorageFile.GetUserStoreForSite();

应用程序配置更名

应用程序设置ApplicationSettings类更名为IsolatedStorageSettings,且sealed类。

Beta 1:

ApplicationSettings settings = ApplicationSettings.Default;
settings.Add("myKey", myValue);
settings.Save();

Beta 2

IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
settings.Add("myKey", myValue);
settings.Save();

IsolatedStorageSettings settings = IsolatedStorageSettings.SiteSettings;
settings.Add("myKey", myValue);
settings.Save();

OpenFileDialog变化

Beta 1中OpenFileDialog.ShowDialog方法的返回值为DialogResult,Beta 2中返回变成了bool类型。

其它API

SetValue方法

在Beta 2中,SetValue方法只能设置依赖属性类型的,而不会像在Beta 1中自动进行转换。如:

Beta 1

myButton.SetValue(Canvas.LeftProperty, 100);

Beta 2

object left = 100;
myButton.SetValue(Canvas.LeftProperty, left);

当然本文总结还只是其中的一部分,更为详细的变化大家可以参考MSDN:

http://msdn.microsoft.com/en-us/library/cc645049(VS.95).aspx

顺便说一句:Silverlight 2 Beta 2中文版的开发包已经发布,以前使用中文Visual Studio 2008安装不上的朋友这下可以放心了:)

http://www.microsoft.com/downloads/details.aspx?displaylang=zh-cn&FamilyID=50a9ec01-267b-4521-b7d7-c0dba8866434

抱歉!评论已关闭.