c# - 如何在用户控件中公开 TextBox 文本属性
问题描述
我希望有人可以帮助我确定我肯定是一个愚蠢的错误。
我已经将我正在处理的用户控件划分为它的基本元素。我在用户控件上放置了一个文本框并公开了 TextBox Text 属性,我创建了以下内容
[Browsable(true)]
public override string Text
{
get
{
return textBox1.Text;
}
set
{
textBox1.Text = value;
}
}
除了一个例外,一切似乎都运行良好。当我将控件放在窗体上时,TextBox 会显示控件的名称,即控件 1。我尝试将属性 Default Attribute 设置如下,但没有影响。
DefaultValue((string)null),
如何阻止控件显示控件名称?
感谢您提供任何指导的建议。
解决方案
此问题的解决方案是自定义ParentControlDesigner
,您可以在其中覆盖InitializeNewComponent
设置或清除Text
属性的方法。
例子
using System;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using System.Security.Permissions;
namespace YourProject
{
[DefaultProperty(nameof(Text))]
[DefaultEvent(nameof(TextChanged))]
[Designer(typeof(MyUserControlDesigner))]
public partial class MyUserControl : UserControl
{
public MyUserControl()
{
InitializeComponent();
// Update the base.Text whenever the TextBox.Text property is changed.
textBox1.TextChanged += (s, e) =>
{
if (textBox1.Text != Text) Text = textBox1.Text;
};
}
// Get and set the text of the base property instead of the TextBox's
// to get the TextChanged event raised.
[Browsable(true),
EditorBrowsable(EditorBrowsableState.Always),
DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public override string Text
{
get => base.Text;
set => base.Text = value;
}
protected override void OnTextChanged(EventArgs e)
{
// Update the TextBox.Text property whenever the base property is changed.
if (Text != textBox1.Text) textBox1.Text = Text;
base.OnTextChanged(e);
}
// If you need to handle the TextChanged event...
/// <inheritdoc cref="Control.TextChanged"/>
[Browsable(true), EditorBrowsable(EditorBrowsableState.Always)]
public new event EventHandler TextChanged
{
add { base.TextChanged += value; }
remove { base.TextChanged -= value; }
}
}
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public class MyUserControlDesigner : ParentControlDesigner
{
public override void InitializeNewComponent(IDictionary defaultValues)
{
base.InitializeNewComponent(defaultValues);
if (Component is MyUserControl c) c.Text = "StephenH"; // c.Text = "";
}
}
}
推荐阅读
- java - 当我从屏幕返回时调用 OnChanged ()?
- c++ - 简单的互斥保护队列与 C++ 中的线程安全队列
- node.js - 如何使用 $lookup 而不是填充
- php - Laravel 迁移相同的外键依赖于 2 个不同的表
- kubernetes - 为什么 Kubernetes 返回未经授权的错误?
- react-native - Expo - 在物理设备上运行时独立 APK 崩溃;在 expo-cli 上运行的应用程序
- java - 通过java 8中的收集器max函数找出具有最大年龄的员工列表
- java - @PathVariable 与 @RequestBody(哪一个以及何时?)
- android-studio - 在 Project Navigator 的 Android Studio 中隐藏文件更新日期
- javascript - 无法在带有 DataTables 的 search.dt 搜索事件中使用 html() 以添加加载消息