How do you implement default text for a search box in WPF?

后端 未结 6 892
醉话见心
醉话见心 2021-01-05 07:09

I want to implement something exactly like \"Changing the Default Text in the Search Box\" for a WPF search TextBox. The box should show some greyed out \"Search..\" text wh

6条回答
  •  渐次进展
    2021-01-05 07:45

    As always in WPF, there are many ways to achieve your goal.

    Perhaps the cleanest way is to subclass TextBox and add a new property called HintText. The template for your control would display HintText (probably in italics and gray) as long as Text is empty (""). Otherwise, it would display the Text just like a regular TextBox.

    An alternative that doesn't involve writing your own control is to re-template TextBox and use the Tag property to store the hint text.

    Another alternative is to write a UserControl that combines a TextBox with, say, a TextBlock inside the same Grid. The TextBlock would contain the hint text and would only be displayed if the TextBox's Text is empty. This is probably the easiest to achieve, but is also the least flexible.

提交回复
热议问题