Reputation: 10638
I need all my textboxes to have a default text so I have done what is explained in this another post. I have used the solution proposed by Steve Greatrex and marked as accepted.
It is working for me but now I am trying to improve it to use in multiple textboxes as a template but for each of my textboxes I want to set a custom different default text.
As template default text is set to whatever, for example "Your Prompt Here" in above link, then all the textboxes I bind this template will have the same text.
I would like to put a different default text for each of my textboxes so how can I do it using the same controltemplate for all the textboxes?
Under "Windows.Resources" I have created an style that cotains the template indicated in the above post:
<Style x:Key="DefaultText" TargetType="TextBox">
<Setter Property="Template">
<Setter.Value>
<!-- here the controltemplate from the above post -->
</Setter.Value>
</Setter>
</Style>
and I use it in my textboxes in the following way:
<TextBox Style="{StaticResource DefaultText}"/>
Upvotes: 0
Views: 7253
Reputation: 2128
Use custom attached property instead of the Tag
which has no any specific semantic:
public static class TextBoxHelper
{
public static readonly DependencyProperty DefaultTextProperty = DependencyProperty.RegisterAttached(
"DefaultText",
typeof(string),
typeof(TextBoxHelper));
[AttachedPropertyBrowsableForType(typeof(TextBox))]
public static string GetDefaultText(FrameworkElement element)
{
return (string)element.GetValue(DefaultTextProperty);
}
public static void SetDefaultText(FrameworkElement element, string value)
{
element.SetValue(DefaultTextProperty, value);
}
}
Then you can use it from XAML:
xmlns:helpers="<your_namespace_with_helpers>"
<TextBox helpers:TextBoxHelper.DefaultText="..."/>
Then in your ControlTemplate
you can set Text
like this:
Text="{Binding Path=(helpers:TextBoxHelper.DefaultText), RelativeSource={RelativeSource TemplatedParent}}"
Although this approach is more verbose than using the Tag
property I recommend you to use it because:
Tag
property which can contain anything since its type is object
.DefaultText
attached property has strict semantic. Anyone can say what it needed for just looking on its name and type.Rule of thumb is always try to avoid using of properties with undefined semantic.
Upvotes: 1
Reputation: 10638
I have solved it by replacing Text property in textblock within control template by this one:
Text="{TemplateBinding Tag}"
then I call it from any textbox like below:
<TextBox Style="{StaticResource WatermarkedTextBox}"
Tag="Type whatever here" />
You can choose default text for each textbox by specifying the Tag property.
Also, this solution does not require the aero theme.
The solution that Clemens propose in this link also works and it is based on aero theme.
Upvotes: 0