【问题标题】:explanation of OnNavigatedTo method in DetailsPage.xaml.cs in windows phone databound appwindows phone 数据绑定应用程序 DetailsPage.xaml.cs 中 OnNavigatedTo 方法的说明
【发布时间】:2014-02-15 07:08:52
【问题描述】:
  protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        if (DataContext == null)
        {
            string selectedIndex = "";
            if (NavigationContext.QueryString.TryGetValue("selectedItem", out selectedIndex))
            {
                int index = int.Parse(selectedIndex);
                DataContext = App.ViewModel.Items[index];
            }
        }
    }

这是来自 Windows phone 数据绑定应用程序中 DetailsPage.xaml.cs 的代码 sn-p。 请逐行解释此代码块的工作原理。

【问题讨论】:

    标签: c# visual-studio data-binding windows-phone-8


    【解决方案1】:

    检查一下,解释在正在解释的代码行下:

    if (DataContext == null)
    

    仅在当前为空(尚未设置)时设置 DataContext。

    if (NavigationContext.QueryString.TryGetValue("selectedItem", out selectedIndex))
    

    尝试获取具有参数 key = "selectedItem" 的查询字符串参数值。如果查询字符串中存在该参数,则TryGetValue函数将返回true,否则将返回false。因此,只有在查询字符串中提供了“selectedItem”参数时,才会执行接下来的 2 行代码。

    int index = int.Parse(selectedIndex);
    

    将字符串值从selectedIndex 解析为整数值。

    DataContext = App.ViewModel.Items[index];
    

    将 DetailsPage 的 DataContext 设置为存储在索引 = index 处的 Items 属性中的对象。 .

    【讨论】:

      【解决方案2】:
      if (NavigationContext.QueryString.TryGetValue("selectedItem", out selectedIndex))
      

      我能理解的是,当页面加载时,QueryString 加载了 Dictionary 类的实例。 然后使用这个实例调用 TryGetValue 方法。这里 selectedItem 是字典类中元素的键,第二个参数确保只有当且仅当字典类中存在键为“selectedItem”的元素时,该方法才返回 true。 或者,如果我们提供的查询字符串包含“selectedItem”。

      int index = int.Parse(selectedIndex);
      

      Selected Index 包含与该键关联的值,但它在字符串中,因此我们使用 int 类的 parse 方法将其转换为整数类型并将其存储在索引变量中。

      DataContext = App.ViewModel.Items[index];
      

      然后将 DetailPage 的 DataContext 设置为集合 Items 中位置等于 index 的对象。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-16
        • 1970-01-01
        • 2013-03-26
        • 2012-10-08
        • 2015-08-28
        • 1970-01-01
        相关资源
        最近更新 更多