Articles in this section
Category / Section

How to centrally align the watermark text in SfTextBoxExt without editing the template?

1 min read

Set Watermark property

Set the watermark property with the desired watermark text, for example ”Type here”.

Retrieve the ContentControl holding Watermark

Use the VisualTreeHelper class to find all the ContentControls in SfTextBoxExt template. You can identify the ControlControl holding the watermark by the name “PART_Watermark”.

Setting alignment

Set HorizontalAlignment=”Center for the ContentControl.

MainPage.xaml

<Page
    x:Class="SfTextBoxExt_132348.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:SfTextBoxExt_132348" xmlns:sync="using:Syncfusion.UI.Xaml.Controls.Input"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <sync:SfTextBoxExt  x:Name="text" Watermark="Type here" Height="30" Width="200"/>
    </Grid>
</Page>

MainPage.xaml.cs

public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            text.Loaded += text_Loaded;   
        }
        void text_Loaded(object sender, RoutedEventArgs e)
        {
            foreach (ContentControl control in FindVisualChildren<ContentControl>(text))
            {
                if (control.Name == "PART_Watermark")
                {
                    control.HorizontalAlignment = HorizontalAlignment.Center;
                    break;
                }
            }
        }      
       //Retrieve all ContentControl in Template
        public static IEnumerable<T> FindVisualChildren<T>(DependencyObject parent)
       where T : DependencyObject
        {
            List<T> foundChilds = new List<T>();
            int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < childrenCount; i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);
                T childType = child as T;
                if (childType == null)
                {
                    foreach (var other in FindVisualChildren<T>(child))
                        yield return other;
                }
                else
                {
                    yield return (T)child;
                }
            }
        }
    }

The above code aligns the watermark text to the center and the following screenshot displays the centrally aligned watermarked text.

Figure 1: Center-aligned watermarked text

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment
Access denied
Access denied