1

I am creating a golfing app. It is a 9 hole golf course. I created a page that has 9 separate text blocks that the user can enter in their score for each hole. Then I have a textbox that I want the final score to be put in. I know how to do this if I put a button to just add up all of the scores at the end, but what I am trying to get it to do, is to add them up once the score is put in. So when the user enters in their first score, the total box will put that one in it, then when the second score is put in its respective box, I want it to add that score to the total etc... for all 9 blocks.

I am creating this as a Windows Phone App with C#

private void Calculate_Click(object sender, RoutedEventArgs e) 
{ 
    int x1 = int.Parse(textBox1.Text); 
    int x2 = int.Parse(textBox2.Text); 
    int x3 = int.Parse(textBox3.Text); 
    int x4 = int.Parse(textBox4.Text); 
    int x5 = int.Parse(textBox5.Text); 
    int x6 = int.Parse(textBox6.Text); 
    int x7 = int.Parse(textBox7.Text); 
    int x8 = int.Parse(textBox8.Text); 
    int x9 = int.Parse(textBox9.Text); 
    int total = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9; 
    TotalBlock.Text = total.ToString();
}
4

2 回答 2

0

试试这个:

    textBlock1.OnTextChanged += textChanged();
    textBlock2.OnTextChanged += textChanged();
    ...
    textBlock9.OnTextChanged += textChanged();

    public void textChanged(object sender, EventArgs e){
        int result = Convert.ToInt32(textBlock1.Text) + ... + Convert.ToInt32(textBlock9.Text);
        finalTextBlock.Text = result.ToString();
    }
于 2013-04-27T16:23:12.207 回答
0

如果你先把你TextBlock的 's 放在一个数组中,这会变得简单得多:

private TextBlock[] numberTextBlocks;

// Call this method at some point while setting up your UI
private void Initialize()
{
    this.numberTextBlocks = new TextBlock[] 
    {
         textBlock1, textBlock2, ...
    };

    foreach(t in this.numberTextBlocks)
    {
        t.OnTextChanged += NumberTextBlock_OnTextChanged;
    }
}

private void NumberTextBlock_OnTextChanged(object sender, EventArgs e)
{
    this.RecalculateTotal();
}

private void Calculate_Click(object sender, RoutedEventArgs e) 
{ 
    this.RecalculateTotal();
}

private void RecalculateTotal(object sender, RoutedEventArgs e) 
{ 
    int total = this.numberTextBlocks.Sum(t => int.Parse(t.Text));
    TotalBlock.Text = total.ToString();
}
于 2013-04-28T10:44:51.750 回答