by Sottje
1. April 2010 07:10
On my current project, we make use of the WPF Toolkit. One of the things we use is the Datepicker. A nice usefull control. We wanted to set the watermark, but the control doesn't support setting the watermark with a public property and we didn't want to go into the control's source itself.
On Codeplex, we found a forum topic with a solution (thnx Spud). Derive from the Datepicker control and override the OnRender method. This works and sets the watermark correctly.
But after a date is selected, the value was cleared and the control loses the focus, the default watermark returns again. I fixed this by using the LostFocus event on the textbox. The result is this:
public class SottjeDatePicker : DatePicker
{
private FieldInfo _textboxFieldInfo;
private DatePickerTextBox _dateTextBox;
///
/// Overrides the OnRender methods
///
///
protected override void OnRender(DrawingContext drawingContext)
{
base.OnRender(drawingContext);
_textboxFieldInfo = typeof(DatePicker).GetField("_textBox"
, BindingFlags.Instance | BindingFlags.NonPublic);
if (_textboxFieldInfo != null)
{
_dateTextBox = (DatePickerTextBox)_textboxFieldInfo.GetValue(this);
// Add event to update watermark when needed on lostfocus.
_dateTextBox.LostFocus += OnDateTextBoxLostFocus;
UpdateWatermark();
}
}
///
/// Called when textbox loses focus.
///
/// The sender.
/// The instance containing the event data.
private void OnDateTextBoxLostFocus(object sender
, System.Windows.RoutedEventArgs e)
{
if (_dateTextBox != null && string.IsNullOrEmpty(_dateTextBox.Text))
{
UpdateWatermark();
}
}
///
/// Updates the watermark.
///
private void UpdateWatermark()
{
PropertyInfo watermarkPropertyInfo =
typeof(DatePickerTextBox).GetProperty("Watermark"
, BindingFlags.Instance | BindingFlags.NonPublic);
if (watermarkPropertyInfo != null)
{
string watermark = Properties.Resources.DatePickerWatermark;
watermarkPropertyInfo.SetValue(_dateTextBox, watermark, null);
}
}
}
Have fun!
