Search code examples
c#silverlightsilverlight-4.0windows-phone-7

Passing page checkBox value to other class


I've been reading other questions and pages and seen some ideas but could not understand them or get them to work properly.

My Example:

I have this checkBox1 on my mainpage.xaml

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

I have a anotherpage.xaml with its c# on anotherpage.xaml.cs:

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

        }
     }

How do I pass the value of the checkBox1 on the mainpage.xaml to the anotherpage.xaml.cs


Solution

  • You could pass whether the checkbox is checked when opening the next page:

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

    You could then query this in the OnNavigatedTo event on the "other" page:

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

    Edit:
    To pass multiple values just add them to the query string:

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

    (You'll probably want to format the code a bit better though)

    You can then get each parameter in turn from the

    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))
            {
                //
            }
        }
    }
    

    As you want to pass more and more values this will get messy with lots of duplicate code. Rather than pass multiple values individualy you could concatenate them all together:

    var checks = string.Format("{0}|{1}", checkBox1.IsChecked, checkBox2.IsChecked);
    
    NavigationService.Navigate(new Uri("/AnotherPage.xaml?chks=" + checks, UriKind.Relative));
    

    You could then split the string and parse the parts individually.