如何在c#中的事件处理程序方法中将值从一个函数传递给另一个函数

时间:2014-07-07 09:44:33

标签: c# windows-phone-8 windows-phone-8.1 c#-5.0

我有使用web-client填充的列表框,我使用for循环将对象与json响应分开供我使用,我需要在整个类中使用这些对象,即我需要在所有方法中使用这些值,如果可以从一种方法传递到另一种方法,甚至是可行的

代码:

void Downloadpage()
{
    WebClient webclient = new WebClient();

    webclient.Headers["ContentType"] = "application/json";
    webclient.DownloadStringCompleted += wc_downloadStringCompleted;
    webclient.DownloadStringAsync(new Uri("http://client.web.net/pages_wp.php"), UriKind.RelativeOrAbsolute);          
}

public void wc_downloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    string lreport = e.Result.ToString();
    string lnoHTMLs = Regex.Replace(lreport, @"<[^>]+>|&nbsp;|&zwnj;|&raquo;|&laquo;|&ldquo;|\\n|\\t|", "", RegexOptions.Multiline).Trim();
    string lnoHTMLNormaliseds = Regex.Replace(lnoHTMLs, @"\s{2,}", " ");


    JArray res = JArray.Parse(lnoHTMLNormaliseds);
news = new List<jsons>();


            string rId = res[0]["raportId"].ToString();            ---->a
            string rTitle = res[0]["raportTitle"].ToString();      --->b
            news.Add(new jsons() { raportId = rId, raportTitle = rTitle});


        Presslist.ItemsSource = news;
}

我需要访问&#39; a&#39;和&#39;&#39;在另一个按钮点击事件如下

private void Add_to_cart(object sender, EventArgs e)
{
   //values need to come here
}

注意:点击按钮时会触发Add_to_cart

2 个答案:

答案 0 :(得分:1)

使变量类级别

String _rId ="";
String _rTitle ="";

void Downloadpage()
{
    WebClient webclient = new WebClient();

    webclient.Headers["ContentType"] = "application/json";
    webclient.DownloadStringCompleted += wc_downloadStringCompleted;
    webclient.DownloadStringAsync(new Uri("http://client.web.net/pages_wp.php"),
UriKind.RelativeOrAbsolute);          
}

public void wc_downloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    string lreport = e.Result.ToString();
    string lnoHTMLs = Regex.Replace(lreport, @"<[^>]+>|&nbsp;|&zwnj;|&raquo;|&laquo;|&ldquo;|\\n|\\t|", "", RegexOptions.Multiline).Trim();
    string lnoHTMLNormaliseds = Regex.Replace(lnoHTMLs, @"\s{2,}", " ");


    JArray res = JArray.Parse(lnoHTMLNormaliseds);
news = new List<jsons>();


            string rId = res[0]["raportId"].ToString();           // ---->a
            string rTitle = res[0]["raportTitle"].ToString();     // --->b
            news.Add(new jsons() { raportId = rId, raportTitle = rTitle});
            _rId = rId;
            _rTitle = rTitle;


        Presslist.ItemsSource = news;
}

private void Add_to_cart(object sender, EventArgs e)
{
   //values need to come here
   //_rId
   //_rTitle
}

答案 1 :(得分:1)

我认为您调用Downloadpage()方法的地方可以将这些值保存在一个公共位置。可以是Session LevelApplication level空格。

我认为Add_to_cart()方法是一个按钮点击事件,因此应该在显示UI 之前在页面加载事件或任何事件中调用DownloadPage。 当调用Add_to_cart()时,您可以检索值并使用它们。