65.9K
CodeProject 正在变化。 阅读更多。
Home

Silverlight 4:使用新 API 实现通知

2009年11月21日

CPOL

2分钟阅读

viewsIcon

23719

downloadIcon

350

本文演示了 Silverlight 4 中的所有新通知功能。

引言

Silverlight 通知 API 是 Silverlight 4 Beta 1 中引入的一项新功能。 如果您正在使用 Silverlight 开发应用程序,并希望向用户显示类似 Outlook 的通知消息,则可以使用此功能。 请记住,此功能仅在浏览器外部工作。

背景

要开发 Silverlight 4 应用程序,您需要 Visual Studio 2010 Beta 2,可以从 Microsoft 网站下载。 如果您使用的是 Visual Studio 2008,也可以并排安装 Visual Studio 2010。 安装完工作室后,只需安装“Silverlight 4 Tools for Visual Studio 2010”。

代码的使用

设置好开发环境后,使用 Visual Studio 2010 创建一个新的 Silverlight 4 应用程序。 这将自动为您创建一个“MainPage.xaml”页面。 在 XAML 中添加两个按钮:一个用于将 Silverlight 应用程序安装为浏览器外部应用,另一个用于显示通知。

<Button x:Name="btnInstall" Width="150" 
    Height="20" Content="Install OOB" Margin="5"/>
<Button x:Name="btnShowNotification" Width="150" 
  Height="20" Content="Show Notification" Margin="5"/>

要实现 Silverlight 浏览器外部功能,请参考我之前的文章:“如何实现 Silverlight 3 浏览器外部功能?” 现在转到代码隐藏文件“MainPage.xaml.cs”并实现这些按钮的 Click 事件。 在页面加载时,如果它正在浏览器外部运行,则创建通知窗口实例。

// Initialize a new instance of Notification Window
notificationWindow = new NotificationWindow();
notificationWindow.Height = 50.0;
notificationWindow.Width = 300.0;

使用 XAML 或代码隐藏创建自定义通知面板。 您可以使用一个美观的 UserControl。 例如,我将使用一个 Border 内部的 TextBlock 来显示一个简单的消息。

Border border = new Border()
{
    Background = new SolidColorBrush(Colors.Gray),
    Height = notificationWindow.Height,
    Width = notificationWindow.Width,
    Child = new TextBlock()
    {
        Text = "This is a Custom Notification from Silverlight 4",
        Foreground = new SolidColorBrush(Colors.White)
    }
};

现在,在“显示通知”按钮的单击事件中,检查它是否正在浏览器外部运行。 如果是,则将您创建的通知面板分配给通知窗口实例的内容,并调用通知窗口的 Show 方法。 在这里,您需要以毫秒为单位传递通知的可见持续时间。

notificationWindow.Content = border; // add the custom notification panel
notificationWindow.Show(2000); // show the notification

现在,运行您的应用程序并单击“安装 OOB”按钮。 这将安装 Silverlight 应用程序并打开其桌面版本。 单击“显示通知”按钮以在桌面的右下角显示通知。

© . All rights reserved.