【问题标题】:Passing page checkBox value to other class将页面复选框值传递给其他类
【发布时间】:2010-12-14 20:46:59
【问题描述】:

我一直在阅读其他问题和页面,看到了一些想法,但无法理解它们或让它们正常工作。

我的例子:

我的 mainpage.xaml 上有这个 checkBox1

 <CheckBox Content="Central WC / EC" Height="68" HorizontalAlignment="Left" Margin="106,206,0,0" Name="checkBox1" VerticalAlignment="Top" BorderThickness="0" />

我在 anotherpage.xaml.cs 上有一个带有 c# 的 anotherpage.xaml:

 public void Feed(object Sender, DownloadStringCompletedEventArgs e)
    {
        if (checkBox1.Checked("SE" == (_item.Sector))) ; 
        {

        }
     }

如何将 mainpage.xaml 上 checkBox1 的值传递给 anotherpage.xaml.cs

【问题讨论】:

标签: c# silverlight silverlight-4.0 windows-phone-7


【解决方案1】:

你可以通过打开下一页时是否选中复选框:

NavigationService.Navigate(new Uri("/AnotherPage.xaml?chkd=" + checkBox1.IsChecked, UriKind.Relative));

然后您可以在“其他”页面上的OnNavigatedTo 事件中查询:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    string isChecked;
    if (NavigationContext.QueryString.TryGetValue("chkd", out isChecked))
    {
        if (bool.Parse(isChecked))
        {
            //
        }
    }
}

编辑:
要传递多个值,只需将它们添加到查询字符串中:

NavigationService.Navigate(new Uri("/AnotherPage.xaml?chk1=" + checkBox1.IsChecked + "&chk2=" + checkBox2.IsChecked, UriKind.Relative));

(不过,您可能希望将代码格式设置得更好一些)

然后你可以依次从

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    string is1Checked;
    if (NavigationContext.QueryString.TryGetValue("chk1", out is1Checked))
    {
        if (bool.Parse(is1Checked))
        {
            //
        }
    }

    string is2Checked;
    if (NavigationContext.QueryString.TryGetValue("chk2", out is2Checked))
    {
        if (bool.Parse(is2Checked))
        {
            //
        }
    }
}

当您想要传递越来越多的值时,这会因大量重复代码而变得混乱。您可以将它们连接在一起,而不是单独传递多个值:

var checks = string.Format("{0}|{1}", checkBox1.IsChecked, checkBox2.IsChecked);

NavigationService.Navigate(new Uri("/AnotherPage.xaml?chks=" + checks, UriKind.Relative));

然后您可以拆分字符串并单独解析各个部分。

【讨论】:

  • 嗨,马特,这似乎是一个有趣的解决方案。我可以用它来传递多个复选框吗?我一共有8个。谢谢。
  • @Dan 更新了答案,包括两种处理多个复选框的方法。
【解决方案2】:

您可以在 App 类中声明公共属性。

public partial class App : Application
{
    public int Shared { set; get; }
    //...
}

然后您可以通过以下方式从页面访问它:

(Application.Current as App).Shared

您可以存储对表单的引用或放置事件或您想做的任何其他事情。

另外,我强烈推荐Petzold's WP7 book free for download

【讨论】:

  • 谢谢,我会调查的。
猜你喜欢
  • 2014-08-25
  • 2020-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-13
  • 2012-12-29
  • 1970-01-01
  • 2014-11-22
相关资源
最近更新 更多