如何通过RepeatButton增加和减少数百?

时间:2017-09-22 13:36:18

标签: wpf vb.net

您可以通过以下代码一个来增加和减少数字。

以下代码是okey。

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="400">
<Grid>
    <RepeatButton Width="100" Height="40"  HorizontalAlignment="Left" Name="btnRemove" Content="Remove" Click="btnRemove_Click" />
    <TextBox Width="150" Height="40" Name="txtDisplay" TextAlignment="Center" Text="5000" MaxLength="5" />
    <RepeatButton Width="100" Height="40" HorizontalAlignment="Right" Name="btnAdd" Content="Add" Click="btnAdd_Click" />
</Grid>
</Window>

...

Namespace WpfApplication1

Partial Public Class MainWindow

    Public counter As Integer = 5000

    Private Sub btnAdd_Click(sender As Object, e As RoutedEventArgs)
        txtDisplay.Text = (System.Threading.Interlocked.Increment(counter)).ToString()
    End Sub

    Private Sub btnRemove_Click(sender As Object, e As RoutedEventArgs)
        txtDisplay.Text = (System.Threading.Interlocked.Decrement(counter)).ToString()
    End Sub

End Class

End Namespace

问题:

如何按增加和减少数字?

2 个答案:

答案 0 :(得分:2)

所以你的问题是关于线程安全递增/递减?您可以使用Interlocked.Add

Private Sub btnAdd_Click(sender As Object, e As RoutedEventArgs)
    txtDisplay.Text = System.Threading.Interlocked.Add(counter, 100).ToString()
End Sub

Private Sub btnRemove_Click(sender As Object, e As RoutedEventArgs)
    txtDisplay.Text = System.Threading.Interlocked.Add(counter, -100).ToString()
End Sub

答案 1 :(得分:1)

这个怎么样?

Private Sub btnAdd_Click(sender As Object, e As RoutedEventArgs)
    counter += 100
    If (counter > 6000) Then
        counter = 6000
    End If
    txtDisplay.Text = counter.ToString()
End Sub

Private Sub btnRemove_Click(sender As Object, e As RoutedEventArgs)
    counter -= 100
    If (counter < 0) Then
        counter = 0
    End If
    txtDisplay.Text = counter.ToString()
End Sub

这里没有理由使用System.Threading.Interlocked.Increment,因为事件处理程序总是在同一个线程上执行。