static void ProcesswaterMark(watermarkControl Holder, Size? fitTo = null) { if (Holder.ctrl.IsKeyboardFocused || !String.IsNullOrWhiteSpace(Holder.TextCheckDel(Holder.ctrl))) { Holder.ctrl.Background = System.Windows.Media.Brushes.White; } else { var element = new Grid { Background = System.Windows.Media.Brushes.White, Margin = new Thickness(0), }; if (null != fitTo) { element.Width = fitTo.Value.Width; /* * No need fit height if (fitTo.Value.Width > 5) element.Width = fitTo.Value.Width - 5; if(fitTo.Value.Height > 5) element.Height = fitTo.Value.Height -5; */ } else { element.Width = Holder.ctrl.ActualWidth; } element.Children.Add(new Label { Margin = new Thickness(0), Content = GetWaterMark(Holder.ctrl), Foreground = System.Windows.Media.Brushes.LightGray, //FontStyle = System.Windows.FontStyles.Italic, Background = System.Windows.Media.Brushes.Transparent, FontSize = 10, Opacity = 0.8, HorizontalAlignment = HorizontalAlignment.Left, }); Holder.ctrl.Background = new VisualBrush { AlignmentX = AlignmentX.Left, AlignmentY = AlignmentY.Center, Stretch = Stretch.Fill, Visual = element, }; } }
private static void onWaterMarkChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var holder = new watermarkControl { ctrl = d as Control }; if (holder.ctrl is TextBox) { holder.TextCheckDel = (c)=> ((TextBox)c).Text; ((TextBox)holder.ctrl).TextChanged += (o1, e1) => { ProcesswaterMark(holder); }; } else if (holder.ctrl is PasswordBox) { holder.TextCheckDel = (c) => ((PasswordBox)c).Password; ((PasswordBox)holder.ctrl).PasswordChanged += (o1, e1) => { ProcesswaterMark(holder); }; } else { Debug.WriteLine("Not a valid control type"); return; } holder.ctrl.IsKeyboardFocusedChanged += (o1, e1) => { ProcesswaterMark(holder); }; holder.ctrl.SizeChanged += (o1, e1) => { ProcesswaterMark(holder, e1.NewSize); }; ProcesswaterMark(holder); }