wpf 数字键盘 CS
时间: 2023-08-31 11:11:28 浏览: 147
以下是一个 WPF 数字键盘的示例,包括数字、小数点和清除按钮,并附带 C# 代码实现:
XAML 代码:
```xaml
<Window x:Class="NumericKeypad.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Numeric Keypad" Height="300" Width="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Button Grid.Row="0" Grid.Column="0" Content="1" Click="Button_Click" />
<Button Grid.Row="0" Grid.Column="1" Content="2" Click="Button_Click" />
<Button Grid.Row="0" Grid.Column="2" Content="3" Click="Button_Click" />
<Button Grid.Row="1" Grid.Column="0" Content="4" Click="Button_Click" />
<Button Grid.Row="1" Grid.Column="1" Content="5" Click="Button_Click" />
<Button Grid.Row="1" Grid.Column="2" Content="6" Click="Button_Click" />
<Button Grid.Row="2" Grid.Column="0" Content="7" Click="Button_Click" />
<Button Grid.Row="2" Grid.Column="1" Content="8" Click="Button_Click" />
<Button Grid.Row="2" Grid.Column="2" Content="9" Click="Button_Click" />
<Button Grid.Row="3" Grid.Column="0" Content="." Click="Button_Click" />
<Button Grid.Row="3" Grid.Column="1" Content="0" Click="Button_Click" />
<Button Grid.Row="3" Grid.Column="2" Content="Clear" Click="Button_ClearClick" />
<TextBox Grid.Row="4" Grid.ColumnSpan="3" Margin="5" Text="{Binding Path=Value, Mode=TwoWay}" />
</Grid>
</Window>
```
C# 代码:
```csharp
using System.Windows;
using System.Windows.Controls;
namespace NumericKeypad
{
public partial class MainWindow : Window
{
public decimal Value
{
get { return (decimal)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(decimal), typeof(MainWindow), new PropertyMetadata(0m));
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Button button = (Button)sender;
string content = button.Content.ToString();
decimal number;
if (content == ".")
{
if (Value.ToString().Contains("."))
{
return;
}
number = 0.0m;
}
else
{
number = decimal.Parse(content);
}
Value = Value * 10m + number;
}
private void Button_ClearClick(object sender, RoutedEventArgs e)
{
Value = 0m;
}
}
}
```
在这个示例中,我们使用了一个 TextBox 控件来显示用户输入的数字,并将它的 Text 属性绑定到 Value 属性。在 Value 属性的 setter 中,我们使用 SetValue 方法来通知 WPF 属性已更改。在 Button_Click 事件处理程序中,我们使用 Button 控件的 Content 属性来获取用户输入的数字,并将它们添加到 Value 属性中。如果用户按下小数点按钮,则我们将 Value 属性设置为 0,以便用户可以输入小数。在 Button_ClearClick 事件处理程序中,我们将 Value 属性设置为 0,以便用户可以清除已输入的数字。
您可以根据需要自定义样式和行列定义。
阅读全文