我想为应用程序中的每个 DatePicker 应用一个设定的开始日期,因为重复以下代码片段不是一个好主意。
<DatePicker SelectedDate="{Binding Date}"
DisplayDateStart="05/01/2006"/>
除了在一个地方设置默认的 DisplayDateStart 之外,我还需要能够绑定(bind) DatePicker 的 SelectedDate 属性。
我尝试创建自定义用户控件,但按日历图标没有任何反应(好吧,文本框正在闪烁,但没有出现日历弹出窗口)
<UserControl x:Class="MyWpfAdd.ModDatePicker"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<DockPanel>
DatePicker x:Name="DatePicker" DisplayDateStart="05/01/2006"/>
</DockPanel>
</UserControl>
使用底层代码:
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
namespace MyWpfApp
{
public partial class ModDatePicker : UserControl
{
public DateTime? SelectedDate
{
get => (DateTime?)GetValue(SelectedDateProperty);
set
{
this.DatePicker.SelectedDate = value;
SetValue(SelectedDateProperty, value);
}
}
public static readonly DependencyProperty SelectedDateProperty =
DependencyProperty.Register("SelectedDate", typeof(DateTime?), typeof(ModDatePicker), new PropertyMetadata(null));
public DateTime? DisplayDateEnd
{
get => (DateTime?)GetValue(DisplayDateEndProperty);
set
{
this.DatePicker.DisplayDateEnd = value;
SetValue(DisplayDateEndProperty, value);
}
}
public static readonly DependencyProperty DisplayDateEndProperty =
DependencyProperty.Register("DisplayDateEnd", typeof(DateTime?), typeof(ModDatePicker), new PropertyMetadata(null));
public ModDatePicker()
{
InitializeComponent();
}
}
}
最佳答案
首先创建一个具有静态属性的类,该类提供您需要的默认日期:
public static class DatePickerHelper
{
private static DateTime defaultDisplayDateStart = new DateTime(2006, 1, 5);
public static DateTime DefaultDisplayDateStart
{
get
{
return defaultDisplayDateStart;
}
}
}
然后在 DatePicker
的全局默认样式中使用它:
<Application x:Class="WpfApp1.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp1"
StartupUri="MainWindow.xaml">
<Application.Resources>
<Style TargetType="{x:Type DatePicker}" BasedOn="{StaticResource {x:Type DatePicker}}">
<Setter Property="DisplayDateStart" Value="{x:Static local:DatePickerHelper.DefaultDisplayDateStart}" />
</Style>
</Application.Resources>
</Application>
希望这个提示能帮到你
关于c# - 在所有 DatePicker 上设置默认 DisplayDateStart,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53321073/