计数器 - ;帮帮我理解

时间:2012-06-29 05:55:58

标签: c# windows-phone-7 counter

应用程序,有一个TextBlock和两个按钮,通过单击按钮显示文本TextBlock(Q.txt的文本逐行读取,超过一百行):

public class QWork
{
   public static int counter = 0;

   public static string GetQ()
    {
        var qFile = new List<string>();

        string pathFile = "Q.txt";
        Uri uri = new Uri(pathFile, UriKind.Relative);
        StreamResourceInfo sri = Application.GetResourceStream(uri);
        using (StreamReader sr = new StreamReader(sri.Stream))
        {
            string line = "";
            while (line != null)
            {
                line = sr.ReadLine();
                if (line != null)
                    qFile.Add(line);  // Add to list
            }
            return qFile[counter];
        }
    }
}

按钮事件处理程序:

    private void RightButton_Click(object sender, RoutedEventArgs e)//Next text
    {
        qTextBlock.Text = QWork.GetQ();
        QWork.counter++;
    }

    private void LeftButton_Click(object sender, RoutedEventArgs e)//Previous text
    {
        qTextBlock.Text = QWork.GetQ();
        QWork.counter --;
    }

问题: 当我单击LeftButton时,第一个仍显示以下行,但仅在之前。 请告诉我,我该怎么办呢。

谢谢!

1 个答案:

答案 0 :(得分:2)

也许这可以帮到你

int counter = 0;
List<string> qs = null;

private void LoadQs()
{
    qs = new List<string>();
    qs.Add("aaa");
    qs.Add("bbb");
    qs.Add("ccc");
}

private string GetQ(bool increase)
{
    if (increase)
        counter++;
    else
        counter--;

    if (counter >= qs.Count)
        counter = 0;
    else if (counter <= 0)
        counter = qs.Count;

    string q = qs[counter];

    return q;
}