WPF 实现带标题的TextBox
2021-05-14 11:27
标签:erb sch inf cal pix frame ide mic app 这篇博客将分享在WPF中如何创建一个带Title的TextBox。首先请看一下最终的效果, 实现思路:使用TextBlock+TextBox来实现,TextBlock用来显示Title。 实现代码, TitleTextBox 定义TitleTextBox样式, 在XAML中需要引用TitleTextBox。 使用时设置一下Title即可。使用方式和普通TextBox一样。 以后如果遇到带Title的ComboBox,CheckBox等都可以参考上面的实现思路。 感谢您的阅读,代码点击这里下载。 WPF 实现带标题的TextBox 标签:erb sch inf cal pix frame ide mic app 原文地址:http://www.cnblogs.com/wangchaoyuana/p/7523412.html [TemplatePart(Name = TitleTextBlockKey, Type = typeof(TextBlock))]
public class TitleTextBox : TextBox
{
private const string TitleTextBlockKey = "PART_TitleTextBlock";
private TextBlock _tbkTitle;
public static readonly DependencyProperty TitleProperty;
public string Title
{
get { return (string)GetValue(TitleProperty); }
set { SetValue(TitleProperty, value); }
}
static TitleTextBox()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(TitleTextBox), new FrameworkPropertyMetadata(typeof(TitleTextBox)));
TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(TitleTextBox), new UIPropertyMetadata(new PropertyChangedCallback(TitlePropertyChangedCallback)));
}
private static void TitlePropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TitleTextBox ttb = d as TitleTextBox;
if (ttb._tbkTitle != null)
{
ttb._tbkTitle.Text = (string)e.NewValue;
}
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
_tbkTitle = Template.FindName(TitleTextBlockKey, this) as TextBlock;
_tbkTitle.Text = Title;
}
}
上一篇:C# Settings使用小结