WPF DatePicker:自定义 DisplayText
WPF DatePicker: Custom DisplayText
我的 DatePicker
DisplayDate
应该有自定义格式,但我的问题是,无法使用标准自定义格式标签(如 y
、 yyyy
、d
等等)。
有没有办法可以将 SelectedDate
绑定到 DateTime
属性 并将 DisplayText
绑定到字符串 属性?
那么您可以使用 StringFormat
特定的 DatePicker
日期格式(查看此示例:Changing the string format of the WPF DatePicker)
这是一个简单的示例(确保 ViewModel 是适合您 xaml 文件的 DataContext)
主要Window
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var vm = new ViewModel();
DataContext = vm;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var context = (ViewModel) DataContext;
var date = context.SelectedDate;
MessageBox.Show(string.Format("Selected Date is {0:MM/dd/yy H:mm:ss zzz}", date));
}
}
查看模型
public class ViewModel
{
public DateTime SelectedDate { get; set; }
}
Xaml 文件
<DatePicker VerticalAlignment="Top"
SelectedDate="{Binding SelectedDate}" />
<Button Content="Button"
HorizontalAlignment="Left"
Margin="10,74,0,0"
VerticalAlignment="Top"
Width="75"
Click="Button_Click" />
您可以在显示 MessageBox 时更改 DateTime
的格式(检查:https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx)
更新
对于(yy-day Of Year),您可以使用:
MessageBox.Show(string.Format("Selected Date is {0:yy-}{1}", date, date.DayOfYear));
我认为您可以使用字符串格式 属性 以自定义方式显示日期
Binding="{Binding CustomerParcelDropTime,StringFormat=\{0:dd/MM/yyyy HH:mm:ss \}}"
感谢您的回答。我的问题是没有我需要的格式。我需要以两位数 (yy) 显示年份,但在那之后我需要一年中的第几天,因此没有格式。
我目前的解决方案是编写一个带有普通文本框和日历弹出窗口的用户控件。我只是希望我可以使用标准控件。
我的 DatePicker
DisplayDate
应该有自定义格式,但我的问题是,无法使用标准自定义格式标签(如 y
、 yyyy
、d
等等)。
有没有办法可以将 SelectedDate
绑定到 DateTime
属性 并将 DisplayText
绑定到字符串 属性?
那么您可以使用 StringFormat
特定的 DatePicker
日期格式(查看此示例:Changing the string format of the WPF DatePicker)
这是一个简单的示例(确保 ViewModel 是适合您 xaml 文件的 DataContext)
主要Window
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var vm = new ViewModel();
DataContext = vm;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var context = (ViewModel) DataContext;
var date = context.SelectedDate;
MessageBox.Show(string.Format("Selected Date is {0:MM/dd/yy H:mm:ss zzz}", date));
}
}
查看模型
public class ViewModel
{
public DateTime SelectedDate { get; set; }
}
Xaml 文件
<DatePicker VerticalAlignment="Top"
SelectedDate="{Binding SelectedDate}" />
<Button Content="Button"
HorizontalAlignment="Left"
Margin="10,74,0,0"
VerticalAlignment="Top"
Width="75"
Click="Button_Click" />
您可以在显示 MessageBox 时更改 DateTime
的格式(检查:https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx)
更新
对于(yy-day Of Year),您可以使用:
MessageBox.Show(string.Format("Selected Date is {0:yy-}{1}", date, date.DayOfYear));
我认为您可以使用字符串格式 属性 以自定义方式显示日期
Binding="{Binding CustomerParcelDropTime,StringFormat=\{0:dd/MM/yyyy HH:mm:ss \}}"
感谢您的回答。我的问题是没有我需要的格式。我需要以两位数 (yy) 显示年份,但在那之后我需要一年中的第几天,因此没有格式。 我目前的解决方案是编写一个带有普通文本框和日历弹出窗口的用户控件。我只是希望我可以使用标准控件。