0

应用,有一个TextBlock和两个Button,点击按钮显示文本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 时,第一个仍然显示以下行,但仅在上一个之后。请告诉我,我该如何解决它。

谢谢!

4

1 回答 1

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;
}
于 2012-06-29T06:50:48.823 回答