按钮点击后的代码导航

时间:2014-02-18 03:48:29

标签: c# .net windows-phone-7 windows-phone-8

我有点蠢蠢欲动,想知道在点击按钮后执行某些代码后如何导航到不同的页面?这就是我所拥有的

  private void saveButton_Click(object sender, RoutedEventArgs e)
    {
        try
        {

            address = bitCoinAddress.Text;
            // create directory called locationData
            myIsolatedStorage.CreateDirectory("Contact");
            // create file called location.txt inside locationData directory
            writeFile = new StreamWriter(new IsolatedStorageFileStream("Contact\\me.txt", FileMode.Create, myIsolatedStorage));
            writeFile.WriteLine(address);
            writeFile.Close();
            NavigationService.Navigate(new Uri("/Contacts.xaml", UriKind.Relative));
        }
        catch (Exception b)
        {

            MessageBox.Show("error saving Bitcoin address");
            Console.WriteLine("An error occured:" + b);
        }

1 个答案:

答案 0 :(得分:1)

最明确的是,问题在于这一行:

myIsolatedStorage.CreateDirectory("Contact");

因为在button_click事件中你无法保证,myIsolatedStorage对象仍然存在(它可能已被处理掉,代码应该被包装到中使用来防止这种情况)。用这种方式重写你的代码:

using (myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (!myIsolatedStorage.DirectoryExists("Contact"))
                        myIsolatedStorage.CreateDirectory("Contact");

                    using (writeFile = new StreamWriter(new IsolatedStorageFileStream("Contact\\me.txt", FileMode.Create, myIsolatedStorage)))
                    {
                      writeFile.WriteLine(address);
                    }
                }
NavigationService.Navigate(new Uri("/Contacts.xaml", UriKind.Relative));

这段代码对我来说很好。希望它有所帮助。