Silverlight 4 参数如何传递与使用?

99ANYc3cd6
预计阅读时长 29 分钟
位置: 首页 参数 正文
  1. 应用程序启动参数:当用户启动 Silverlight 应用程序时,可以传递给它的参数。
  2. 页面导航参数:在 Silverlight 应用内部,从一个页面导航到另一个页面时传递的数据。
  3. 方法/函数参数:在编写 C# 或 VB.NET 代码时,方法接收的输入值。
  4. 服务调用参数:在调用 Web 服务(如 WCF、ASMX)或 WCF RIA Services 时传递的参数。

下面我将逐一详细解释这几种参数的使用方法。

silverlight 4 参数
(图片来源网络,侵删)

应用程序启动参数

这是最顶层、最外部的参数,当用户通过浏览器访问一个承载 Silverlight 应用程序的网页时,可以在 URL 中附加查询字符串,Silverlight 应用程序可以读取这些参数。

用途

  • 深度链接:直接打开应用的特定视图或内容,http://yoursite.com/yourapp.xaml?id=123
  • 上下文信息:传递用户标识、来源信息等。

如何获取

Silverlight 应用程序在启动时会触发 Application.Startup 事件,你可以在这个事件的事件处理程序中获取启动参数。

silverlight 4 参数
(图片来源网络,侵删)

示例代码

假设你的 HTML 页面中嵌入 Silverlight 控件的代码如下:

<object data="data:application/x-silverlight-2," type="application/x-silverlight-2">
    <param name="source" value="ClientBin/MyApp.xap"/>
    <param name="onError" value="onSilverlightError" />
    <param name="background" value="white" />
    <param name="minRuntimeVersion" value="4.0.50826.0" />
    <param name="autoUpgrade" value="true" />
    <!-- 在这里添加启动参数 -->
    <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50826.0" style="text-decoration:none">
      <img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="获取 Microsoft Silverlight" style="border-style:none"/>
    </a>
</object>

启动参数是通过 JavaScript 动态添加到 <param name="initParams"> 中的,使用 JavaScript:

function launchSLApp() {
    var slPlugin = document.getElementById("mySilverlightControl");
    slPlugin.content.initParams = "userId=987&theme=dark";
}

在 Silverlight 应用程序的 App.xaml.cs 中,你可以这样读取:

// App.xaml.cs
public partial class App : Application
{
    public App()
    {
        this.Startup += this.Application_Startup;
        this.Exit += this.Application_Exit;
        this.UnhandledException += this.Application_UnhandledException;
        InitializeComponent();
    }
    private void Application_Startup(object sender, StartupEventArgs e)
    {
        // e.InitParams 是一个 NameValueCollection,包含了所有启动参数
        if (e.InitParams != null && e.InitParams.Count > 0)
        {
            string userId = e.InitParams["userId"];
            string theme = e.InitParams["theme"];
            // 使用这些参数,例如设置全局主题或加载特定用户数据
            Debug.WriteLine("启动参数 - UserID: " + userId + ", Theme: " + theme);
        }
        // 导航到主页面
        this.RootVisual = new MainPage();
    }
    // ... 其他代码
}

页面导航参数

在 Silverlight 中,页面之间的导航通常通过 Frame 控件和 UriMapper 来实现,你可以通过修改导航 URI 的查询字符串来传递参数。

用途

  • 打开详情页:从商品列表页点击一个商品,导航到详情页并传递商品ID。
  • 筛选和排序:导航到一个列表页并传递筛选条件。

如何实现

假设你有一个 MainPage 和一个 DetailPage

步骤 1:在 XAML 中设置 Frame 和 UriMapper

MainPage.xaml 中:

<navigation:Frame x:Name="ContentFrame" Source="/Home">
    <navigation:Frame.UriMapper>
        <uriMapper:UriMapper>
            <!-- 将 /ProductDetail?id={productID} 映射到 /Views/DetailPage.xaml -->
            <uriMapper:UriMapping Uri="/ProductDetail?id={id}" MappedUri="/Views/DetailPage.xaml?id={id}"/>
        </uriMapper:UriMapper>
    </navigation:Frame.UriMapper>
</navigation:Frame>

步骤 2:触发导航

MainPage 的代码中,你可以这样导航:

// 在某个按钮的点击事件中
private void Button_Click(object sender, RoutedEventArgs e)
{
    int productId = 123;
    // Frame 会自动使用 UriMapper 进行转换
    this.ContentFrame.Navigate(new Uri("/ProductDetail?id=" + productId, UriKind.Relative));
}

步骤 3:在目标页面接收参数

DetailPage.xaml.cs 中,重写 OnNavigatedTo 方法来获取参数。

// DetailPage.xaml.cs
public partial class DetailPage : Page
{
    public DetailPage()
    {
        InitializeComponent();
    }
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        // e.Uri 是导航到当前页面的完整 URI
        // /ProductDetail?id=123
        // 从 URI 中查询参数
        if (NavigationContext.QueryString.ContainsKey("id"))
        {
            string productIdString = NavigationContext.QueryString["id"];
            int productId;
            if (int.TryParse(productIdString, out productId))
            {
                // 使用 productId 加载产品详情
                LoadProductDetails(productId);
            }
        }
    }
    private void LoadProductDetails(int id)
    {
        // ... 调用服务或从本地数据源加载产品信息
        this.ProductTitleTextBlock.Text = "产品 #" + id + " 的详情";
    }
}

方法/函数参数

这是最基础的编程概念,与 C# 或 VB.NET 的语言特性完全一致。

用途

  • 将数据传递给方法进行处理。
  • 实现代码的复用和模块化。

示例代码

public class Calculator
{
    // 定义一个方法,它接收两个 double 类型的参数
    public double Add(double number1, double number2)
    {
        // 在方法内部使用这些参数
        return number1 + number2;
    }
    // 参数可以有默认值 (C# 4.0 新特性)
    public double GetDiscountedPrice(double originalPrice, double discountRate = 0.1)
    {
        return originalPrice * (1 - discountRate);
    }
}
// 使用方法
Calculator calc = new Calculator();
double sum = calc.Add(10.5, 20.3); // 传递 10.5 和 20.3 作为参数
double finalPrice = calc.GetDiscountedPrice(100.0); // 只传递一个参数,discountRate 使用默认值 0.1
double finalPriceWithCustomDiscount = calc.GetDiscountedPrice(100.0, 0.2); // 传递两个参数

服务调用参数

这是 Silverlight 4 中非常核心的功能,用于与后端服务进行数据交互。

a) 调用传统 WCF / ASMX 服务

在 Silverlight 中调用服务,通常会使用服务引用,你需要在项目中添加“服务引用”,然后客户端会自动生成代理类。

示例代码

假设你有一个 WCF 服务,方法如下:

// 在 WCF 服务中
[ServiceContract]
public interface IProductService
{
    [OperationContract]
    Product GetProductById(int id);
}

在 Silverlight 客户端,你可以这样调用并传递参数:

// 创建服务客户端代理
ProductServiceClient client = new ProductServiceClient();
// 定义回调方法,因为服务调用是异步的
client.GetProductByIdCompleted += (sender, e) =>
{
    if (e.Error == null)
    {
        // 获取服务返回的结果
        Product product = e.Result;
        this.ProductNameTextBlock.Text = product.Name;
    }
    else
    {
        // 处理错误
        MessageBox.Show("获取产品失败: " + e.Error.Message);
    }
};
// 调用服务方法并传递参数
int productId = 456;
client.GetProductByIdAsync(productId); // 异步调用

b) 调用 WCF RIA Services (Silverlight 4 的推荐方式)

RIA Services 简化了 Silverlight 与 .NET 后端的数据交互,它会自动处理数据序列化和验证。

示例代码

假设你有一个 DomainService:

// 在服务器端的 DomainService 中
[EnableClientAccess()]
public class ProductsDomainService : LinqToEntitiesDomainService<MyDbContext>
{
    public IQueryable<Product> GetProducts()
    {
        return this.ObjectContext.Products;
    }
    public Product GetProduct(int id)
    {
        return this.ObjectContext.Products.Where(p => p.Id == id).FirstOrDefault();
    }
}

在 Silverlight 客户端,RIA Services 会自动生成代码,你可以像操作本地对象一样调用:

// 创建 DomainContext
MyDomainContext context = new MyDomainContext();
// 定义查询
var query = context.GetProductsQuery().Where(p => p.Category == "Electronics");
// 加载数据
context.Load(query);
context.LoadCompleted += (sender, e) =>
{
    if (!e.HasError)
    {
        var products = context.Products.Where(p => p.Category == "Electronics").ToList();
        // 绑定到 UI 等
    }
};

对于单个实体,直接调用即可:

context.Load(context.GetProduct(789)); // 传递参数 789
context.LoadCompleted += (sender, e) =>
{
    if (!e.HasError)
    {
        var product = context.Products.FirstOrDefault(); // 获取加载的实体
        // ...
    }
};
参数类型 用途 获取/传递方式 关键点
启动参数 应用启动时传递全局配置或上下文 Application.Startup 事件中的 StartupEventArgs.InitParams 用于深度链接,一次性获取。
导航参数 页面间传递数据,如ID、筛选条件 NavigationContext.QueryString 需配合 FrameUriMapper 使用,在 OnNavigatedTo 中获取。
方法参数 基础编程,向方法传递数据 C# / VB.NET 语法,定义在方法括号内 编程基础,支持值类型、引用类型、默认值等。
服务参数 与后端服务交互,传递查询或操作数据 服务代理方法调用(如 client.MethodAsync(param) Silverlight 4 中主流是 WCF RIA Services,简化了数据操作。

理解这四种参数及其使用场景,是掌握 Silverlight 4 应用程序开发的关键。

-- 展开阅读全文 --
头像
Precision 5510拆机步骤详解?
« 上一篇 01-04
糖猫儿童手表客服电话是多少?
下一篇 » 01-04

相关文章

取消
微信二维码
支付宝二维码

最近发表

标签列表

目录[+]