昨天一个朋友向我求助一个自定义水印控件绑定的问题,问题出在文本框中输入的文本,不能绑定到
相应的依赖属性上(自定义的依赖属性 PassText),他纠结了很久找不出问题所在。问题帮他解决后,这里稍
做总结。
问题描述:
1)默认显示效果:
2)在“水印密码框”中输入四个 ‘a’:
3)单击按钮,打印出密码框中的字符串,但是密码框中的文字并没有显示,显示的还是定义依赖属性时
的默认值:
他的部分源代码:
1)密码框控件类继承自 TextBox ,其中依赖属性 PassText 为绑定到密码框的属性:
public class WaterPasswordBox : TextBox { public static readonly DependencyProperty PassTextProperty = DependencyProperty.Register( "PassText", typeof( string ), typeof( WaterPasswordBox ), new PropertyMetadata( "空" ) ); public string PassText { get { return (string)GetValue( PassTextProperty ); } set { SetValue( PassTextProperty, value ); } } public static DependencyProperty WaterContentProprty = DependencyProperty.Register("WaterContent", typeof(object), typeof(WaterPasswordBox), new PropertyMetadata("水印密码框")); public object WaterContent { get { return GetValue(WaterContentProprty); } set { SetValue(WaterContentProprty, value); } } public static DependencyProperty WaterForegroundProprty = DependencyProperty.Register("WaterForeground", typeof(Brush), typeof(WaterPasswordBox), new PropertyMetadata(new SolidColorBrush(Colors.Gray))); public Brush WaterForeground { get { return (Brush)GetValue(WaterForegroundProprty); } set { SetValue(WaterForegroundProprty, value); } } public WaterPasswordBox() { DefaultStyleKey = typeof(WaterPasswordBox); } ContentControl WaterContentElement = null; PasswordBox PasswordBoxElement = null; public override void OnApplyTemplate() { base.OnApplyTemplate(); WaterContentElement = this.GetTemplateChild("WaterCoElement") as ContentControl; PasswordBoxElement = this.GetTemplateChild("ContentElement") as PasswordBox; if (WaterContentElement != null && PasswordBoxElement != null) { if (string.IsNullOrEmpty(PasswordBoxElement.Password)) WaterContentElement.Visibility = System.Windows.Visibility.Visible; else WaterContentElement.Visibility = System.Windows.Visibility.Collapsed; } } protected override void OnGotFocus(RoutedEventArgs e) { if (WaterContentElement != null && string.IsNullOrEmpty(PasswordBoxElement.Password)) WaterContentElement.Visibility = Visibility.Collapsed; base.OnGotFocus(e); } // public event TextChangedEventHandler TextChanged += ; protected override void OnLostFocus(RoutedEventArgs e) { if (WaterContentElement != null && string.IsNullOrEmpty(PasswordBoxElement.Password)) WaterContentElement.Visibility = Visibility.Visible; base.OnLostFocus(e); } }