怎么设置WPF的DatePicker默认显示“请选择一个日期”
1个回答
2016-09-13
展开全部
可以,方法有2种,一种是用代码,一种是重写样式,我来演示一下用代码怎么实现
//首先在你的App类,即创建项目的时候App.xaml下的类
public partial class App : Application
{
//在启动方法中为时间控件注册一个加载事件
void app_Startup(object sender,StartupEventArgs e)
{
EventManager.RegisterClassHandler(typeof(DatePicker),
FrameworkElement.LoadedEvent,
new RoutedEventHandler(DatePicker_Loaded));
}
void DatePicker_Loaded(object sender, RoutedEventArgs e)
{
var dp = sender as DatePicker;
if (dp == null) return;
var wm = RecursionFindControl<ContentControl>(dp, "PART_Watermark");
if (wm == null) return;
//重新默认水印值
wm.Content = "请选择一个日期";
}
/// <summary>
/// 递归寻找指定名称和指定类型的控件(辅助方法)
/// </summary>
/// <typeparam name="T">寻找的类型</typeparam>
/// <param name="reference">对象</param>
/// <param name="controlName">需要寻找的控件名称</param>
/// <param name="maxLevel">最大递归级数</param>
/// <param name="currentLevel">当前已经递归的级数</param>
/// <returns>返回寻找的类型</returns>
public static T RecursionFindControl<T>(DependencyObject reference, string controlName = "", int maxLevel = int.MaxValue, int currentLevel = 1) where T : class
{
DependencyObject obj = null;
if (reference == null)
{
return obj as T;
}
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(reference); i++)
{
obj = VisualTreeHelper.GetChild(reference, i);
FrameworkElement elemnt = obj as FrameworkElement;
if (elemnt == null)
{
break;
}
if (elemnt is T &&
((!string.IsNullOrEmpty(controlName)
&& elemnt.Name == controlName)
|| string.IsNullOrEmpty(controlName)))
{
return obj as T;
}
else
{
if (currentLevel < maxLevel)//递归层级限制
{
obj = RecursionFindControl<T>(obj, controlName, maxLevel, currentLevel + 1) as DependencyObject;
if (obj != null)
{
return obj as T;
}
}
}
}
return obj as T;
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询