自定义LabelTextBox控件
一、界面设计的需求
界面设计中,需要如下界面

二、解决方案
1.最笨拙的代码
xaml中,最原始的设计方法可能使用到如下代码,可以看到代码段很多是重复的。如果十几个学科写下来,要占用很大篇幅,这是最不理想的方法。

2. 解决问题的思路
针对存在的问题,可以利用自定义控件.来达到重复利用,减少代码使用量,方便快捷的目的。
3. 实践过程
这里没有采用规范的自定义方式。而是在项目中直接生成控件的方式来实现。其原理相同:
实现过程如下:
Step 1:新建一个类 LabelTextBox,继承自TextBox,自定义一个Label依赖属性。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace ScoreTools.CustomControl
{
public class LabelTextBox : TextBox
{
static LabelTextBox()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(LabelTextBox), new FrameworkPropertyMetadata(typeof(LabelTextBox)));
}
public static readonly DependencyProperty LabelProperty = DependencyProperty.Register("Label", typeof(Object), typeof(LabelTextBox), new PropertyMetadata(string.Empty));
public static readonly DependencyProperty LabelPositionProperty = DependencyProperty.Register("LabelPosition", typeof(Position), typeof(LabelTextBox), new PropertyMetadata(Position.Top));
public Object Label
{
get {
return (Object)GetValue(LabelProperty); }
set {

本文记录了在WPF中开发一个自定义LabelTextBox控件的过程,以满足界面设计需求。首先阐述了界面设计中对于这种控件的需求,然后讨论了最原始的代码实现方法及其不足。接着,提出了通过自定义控件来解决代码冗余的问题,详细介绍了创建LabelTextBox类,定义Label依赖属性,以及创建样式文件和设置主题资源的步骤。最后,说明了如何在前端使用自定义的LabelTextBox控件。
最低0.47元/天 解锁文章
578

被折叠的 条评论
为什么被折叠?



