增加手势匹配的分数计数器

时间:2014-04-01 16:58:44

标签: c# wpf counter

我有以下方法在我的应用程序中手势匹配时调用,但计数器仅在方法中递增一次,因此在初始匹配后的每个附加匹配都不会增加计数器和标签。如果这是我的反逻辑中的缺陷或者我应该以不同的方式实现计数器,有人可以看到哪里?

这是我目前的解决方案,只在第一场比赛时增加:

void matcher_GestureMatch(Gesture gesture)
        {
            int scoreCntr = 0;
            lblGestureMatch.Content = gesture.Name;
            scoreCntr++;

            var soundEffects = Properties.Resources.punchSound;
            var player = new SoundPlayer(soundEffects);
            player.Load();
            player.Play();

            lblScoreCntr.Content = scoreCntr;

        }

2 个答案:

答案 0 :(得分:2)

每次运行该方法时,您都将计数重置为0。最快的修复只是在方法之外声明变量:

int scoreCntr = 0;
void matcher_GestureMatch(Gesture gesture)
{
    lblGestureMatch.Content = gesture.Name;
    scoreCntr++;

    var soundEffects = Properties.Resources.punchSound;
    var player = new SoundPlayer(soundEffects);
    player.Load();
    player.Play();

    lblScoreCntr.Content = scoreCntr;
}

答案 1 :(得分:1)

您需要将scoreCntr移出方法范围。当该方法运行时它只是“活着”,所以你想在它所在的类的生命周期中保持它活着。这是一个它看起来像的例子:

    private int scoreCntr = 0;

    void matcher_GestureMatch(Gesture gesture)
    {
        lblGestureMatch.Content = gesture.Name;
        Interlocked.Increment(ref scoreCntr);

        var soundEffects = Properties.Resources.punchSound;
        var player = new SoundPlayer(soundEffects);
        player.Load();
        player.Play();

        lblScoreCntr.Content = scoreCntr;
    }