我正在寻找一个简单的WPF NumericUpDown(又称数字微调器)控件。在WPF中,这似乎是另一个缺失的控件。肯定有一些现有的控件,我不想重复造轮子。
我正在寻找一个简单的WPF NumericUpDown(又称数字微调器)控件。在WPF中,这似乎是另一个缺失的控件。肯定有一些现有的控件,我不想重复造轮子。
扩展的 WPF 工具包有一个:NumericUpDown
原始的WPF控件集中缺少但广泛使用的控件是NumericUpDown控件。它是一种简洁的方式,可以让用户在一个小区域内选择一个固定范围内的数字。虽然可以使用滑块,但对于水平空间有限的紧凑表单来说,NumericUpDown是必不可少的。
解决方案A(通过WindowsFormsHost)
您可以通过在WindowsFormsHost中托管它来在WPF中使用Windows Forms NumericUpDown控件。请注意,您必须包括对System.Windows.Forms.dll程序集的引用。
<Window x:Class="WpfApplication61.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<WindowsFormsHost>
<wf:NumericUpDown/>
</WindowsFormsHost>
...
B方案(自定义)
现有一些商业和Codeplex版本,但都涉及到将第三方dll和开销安装到您的项目中。更简单的方法是构建自己的版本,使用ScrollBar是一个简单的方法。
一个没有Thumb(只有重复按钮)的垂直ScrollBar实际上就是我们想要的。它继承自RangeBase,因此具有我们需要的所有属性,例如Min、Max和SmallChange(设置为1,以限制其为整数值)。
所以我们改变ScrollBar ControlTemplate。首先,我们删除Thumb和水平触发器动作。然后,我们将剩余部分分组到网格中,并添加一个TextBlock来显示数字:
<Grid Margin="2">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock VerticalAlignment="Center" FontSize="20" MinWidth="25" Text="{Binding Value, RelativeSource={RelativeSource TemplatedParent}}"/>
<Grid Grid.Column="1" x:Name="GridRoot" Width="{DynamicResource {x:Static SystemParameters.VerticalScrollBarWidthKey}}" Background="{TemplateBinding Background}">
<Grid.RowDefinitions>
<RowDefinition MaxHeight="18"/>
<RowDefinition Height="0.00001*"/>
<RowDefinition MaxHeight="18"/>
</Grid.RowDefinitions>
<RepeatButton x:Name="DecreaseRepeat" Command="ScrollBar.LineDownCommand" Focusable="False">
<Grid>
<Path x:Name="DecreaseArrow" Stroke="{TemplateBinding Foreground}" StrokeThickness="1" Data="M 0 4 L 8 4 L 4 0 Z"/>
</Grid>
</RepeatButton>
<RepeatButton Grid.Row="2" x:Name="IncreaseRepeat" Command="ScrollBar.LineUpCommand" Focusable="False">
<Grid>
<Path x:Name="IncreaseArrow" Stroke="{TemplateBinding Foreground}" StrokeThickness="1" Data="M 0 0 L 4 4 L 8 0 Z"/>
</Grid>
</RepeatButton>
</Grid>
</Grid>
参考资料:
添加一个文本框和滚动条
在VB中
Private Sub Textbox1_ValueChanged(ByVal sender As System.Object, ByVal e As System.Windows.RoutedPropertyChangedEventArgs(Of System.Double)) Handles Textbox1.ValueChanged
If e.OldValue > e.NewValue Then
Textbox1.Text = (Textbox1.Text + 1)
Else
Textbox1.Text = (Textbox1.Text - 1)
End If
End Sub
<WpfElements:SpinDecorator>
<WpfElements:IntegerTextBox Text="{Binding Foo}" />
</WpfElements:SpinDecorator>