WPF 仿照ElementUI实现时间选择器(TimePicker)
在WPF中,要实现类似ElementUI的时间选择器(TimePicker),你可以使用自定义控件或现有的第三方库。以下是一个简单的自定义时间选择器的例子:
- 创建一个新的WPF用户控件(UserControl)。
- 向用户控件中添加两个ComboBox来分别选择小时和分钟。
- 绑定数据到ComboBox并实现交互。
这是一个基本的实现示例:
<UserControl x:Class="WpfTimePicker.TimePickerControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="120" Height="30">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBlock Text="Hour" VerticalAlignment="Center" Margin="5,0"/>
<ComboBox x:Name="HourComboBox" Width="50" Margin="5,0" Grid.Column="1"/>
<TextBlock Text=":" VerticalAlignment="Center" Grid.Column="2"/>
<ComboBox x:Name="MinuteComboBox" Width="50" Margin="5,0" Grid.Column="3"/>
</Grid>
</UserControl>
using System;
using System.Windows.Controls;
namespace WpfTimePicker
{
public partial class TimePickerControl : UserControl
{
public TimePickerControl()
{
InitializeComponent();
InitializeHourComboBox();
InitializeMinuteComboBox();
}
private void InitializeHourComboBox()
{
for (int i = 0; i < 24; i++)
{
HourComboBox.Items.Add($"{i:D2}");
}
HourComboBox.SelectedIndex = 0;
HourComboBox.SelectionChanged += HourComboBox_SelectionChanged;
}
private void InitializeMinuteComboBox()
{
for (int i = 0; i < 60; i++)
{
MinuteComboBox.Items.Add($"{i:D2}");
}
MinuteComboBox.SelectedIndex = 0;
}
private void HourComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// Update MinuteComboBox if needed
}
public DateTime SelectedTime
{
get
{
int hour = int.Parse(HourComboBox.SelectedItem.ToString().Substring(0, 2));
int minute = int.Parse(MinuteComboBox.SelectedItem.ToString().Substring(0, 2));
return new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, hour, minute,
评论已关闭