using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace FWindSoft.Wpf.Controls { public class TextWatermark { public static readonly DependencyProperty ShowInfoProperty = DependencyProperty.RegisterAttached("ShowInfo", typeof(string), typeof(TextWatermark), new PropertyMetadata(string.Empty, OnShowChanged)); public static readonly DependencyProperty UseWatermarkProperty = DependencyProperty.RegisterAttached("UseWatermark", typeof(bool), typeof(TextWatermark), new PropertyMetadata(false, OnShowChanged)); private static readonly DependencyProperty RefTriggerProperty = DependencyProperty.RegisterAttached("RefTrigger", typeof(MultiTrigger), typeof(TextWatermark)); [AttachedPropertyBrowsableForType(typeof(TextBox))] public static string GetShowInfo(DependencyObject obj) { return (string)obj.GetValue(ShowInfoProperty); } [AttachedPropertyBrowsableForType(typeof(TextBox))] public static void SetShowInfo(DependencyObject obj, string value) { obj.SetValue(ShowInfoProperty, value); } [AttachedPropertyBrowsableForType(typeof(TextBox))] public static bool GetUseWatermark(DependencyObject obj) { return (bool)obj.GetValue(UseWatermarkProperty); } [AttachedPropertyBrowsableForType(typeof(TextBox))] public static void SetUseWatermark(DependencyObject obj, bool value) { obj.SetValue(UseWatermarkProperty, value); } /* 可以使用蒙版的形式 */ public static void OnShowChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { TextBox textBox = d as TextBox; if (textBox == null) return; //创建触发器 Style style = null; try { style = new Style() {TargetType=typeof(TextBox)}; if (textBox.Style != null) { #region 复制style style.BasedOn = textBox.Style; #endregion } //else //{ // style = new Style(); //} var oldTrigger = (MultiTrigger)textBox.GetValue(TextWatermark.RefTriggerProperty); if (oldTrigger != null) { style.Triggers.Remove(oldTrigger); } if (!GetUseWatermark(textBox)) { return; } MultiTrigger multiTrigger = new MultiTrigger(); //暂时不需要交点控制 //multiTrigger.Conditions.Add(new Condition(TextBox.IsFocusedProperty, false)); multiTrigger.Conditions.Add(new Condition(TextBox.TextProperty, string.Empty)); Setter setter = new Setter(); setter.Property = TextBox.BackgroundProperty; setter.Value = new VisualBrush() { AlignmentX = AlignmentX.Left, AlignmentY = AlignmentY.Top, Stretch = Stretch.None, Visual = new TextBlock() { Text = GetShowInfo(textBox), Background = (Brush)textBox.GetValue(TextBox.BackgroundProperty), //Brushes.Transparent, Foreground = Brushes.Gray, FontSize = textBox.FontSize, } }; multiTrigger.Setters.Add(setter); textBox.SetValue(TextWatermark.RefTriggerProperty, multiTrigger); style.Triggers.Add(multiTrigger); textBox.Style = style; } catch (Exception ex) { throw; } } } }