1
votes

I'm building a custom control in Silverlight, extending TextBox. The purpose of the control is to provide a watermark logic (default text, typically used in search boxes). I managed that, when accessing the Text property, it will return string.Empty if Text == Watermark. Indeed, you don't want to consider something like "Enter name here" as a relevant value. When it comes to TwoWay databinding, things get more complicated.

I created a ValueConverter, that takes as parameter the watermark and returns string.Empty if Text == Watermark, Text otherwise. I want the control to be very ease to use, so it would be cool if the client code wouldn't have to specify each time that converter when binding to the Text property. Instead, the converter would be plugged inside the custom control, on the binding object related to the Text property.

I tried the following code, but it crashes because the binding object cannot be modified once it has been assigned. I tried that code in the Load() and OnApplyTemplate() events.

var watermarkedTextBox = (WatermarkedTextBox)dependencyObject;
var textBindingExpression = watermarkedTextBox.GetBindingExpression(TextProperty);
if (textBindingExpression != null)
{
    var textBinding = textBindingExpression.ParentBinding;
    textBinding.Converter = new WatermarkConverter();
    textBinding.ConverterParameter = watermarkedTextBox.Watermark;
    watermarkedTextBox.SetBinding(TextProperty, textBinding);
}

So I need to intercept the binding object at the right time (where it's still allowed to modify it). Any ideas ?

Thanks in advance,

Thibaut

2

2 Answers

1
votes

All right, discussed this with colleagues, found the optimal solution.

The watermark is defined in the ControlTemplate of the custom control. It's a TextBlock added in the TextBox, hidden on focus, shown if text is empty. Code is much better like that :

  • No need to play with the Text property and change it under certain conditions to change it to watermark, or change it to string.Empty so the watermark text is never returned (was error prone)
  • Watermark text style can be directly template bound (TemplateBinding), so it's great, without any C# code, client will be able to customize the appearance of the watermark : color, italicize and more
  • Offers new possibilities (image watermark textbox almost for free)

See you ;)

0
votes

I haven't tried it yet but the Silverlight 4 Textbox has a Watermark property.