gpt4 book ai didi

c# - 在 C# 中设置自定义控件的默认大小/文本

转载 作者:行者123 更新时间:2023-11-30 15:23:35 25 4
gpt4 key购买 nike

我正在我的 C# 应用程序中创建自定义控件以添加新属性(下面的 MyProperty)。它继承自标签。我希望它做的一件事是,当我将它拖到我的表单 (200x132) 上时以特定大小显示。我也希望它不显示任何文字。但是,无论我如何尝试这样做,它似乎都不起作用。但是,我可以毫无问题地设置 BackColor 和 BorderStyle。我是 C# 的新手,所以我可能遗漏了一些明显的东西。

这是我的代码:

using System.Drawing;
using System.Windows.Forms;

namespace MyProgram
{

public enum MyEnum
{
Value1, Value2, Value3
}

public partial class MyControl : Label
{

public MyControl()
{
BackColor = Color.LightCoral;
BorderStyle = BorderStyle.FixedSingle;
AutoSize = false;
Size = new Size(200, 132);
Text = "";
InitializeComponent();
}

protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
}

private MyEnum myProperty;

public MyEnum MyProperty
{
get { return myProperty; }
set { myPropery = value; }
}
}
}

最佳答案

在我看来,通过 Dispersia 的链接提供的答案有一个错误。文本重置应该发生一次,之后用户所做的任何事情都无关紧要。在 Dispersia 的链接中,您实际上无法将文本设置回控件名称,因为它会一直空白。

cramopy 提供的答案在技术上并不能回答您的问题,但它是一种通过在 UserControl 上使用默认值来实现的方法。您还需要将 UserControlText 属性绑定(bind)到标签的属性。

以下内容在继承自 Label 时应该可以工作,并且只会重置一次 Text 属性。

public partial class MyControl : Label
{

#region fields

private IComponentChangeService _changeService;
private bool canResetText = false;

#endregion

#region properties

protected override Size DefaultSize
{
get { return new Size(200, 132); }
}

[Browsable(false)]
public override bool AutoSize
{
get { return false; }
set { base.AutoSize = false; }
}

public override ISite Site
{
get { return base.Site; }
set
{
base.Site = value;

if (!base.DesignMode)
return;

this._changeService = (IComponentChangeService)base.GetService(typeof(IComponentChangeService));

if (this._changeService != null)
this._changeService.ComponentChanged += new ComponentChangedEventHandler(this.OnComponentChanged);
}
}

#endregion

#region constructors

public MyControl()
{
base.BackColor = Color.LightCoral;
base.BorderStyle = BorderStyle.FixedSingle;
}

#endregion

#region methods

protected override void InitLayout()
{
base.InitLayout();

this.canResetText = true;
}

private void OnComponentChanged(object sender, ComponentChangedEventArgs ce)
{
if (ce.Component != null &&
ce.Component == this &&
ce.Member.Name == "Text" &&
base.DesignMode &&
this.canResetText)
{
((MyControl)ce.Component).Text = string.Empty;

this.canResetText = false;

if (this._changeService != null)
this._changeService.ComponentChanged -= new ComponentChangedEventHandler(this.OnComponentChanged);
}
}

#endregion

}

关于c# - 在 C# 中设置自定义控件的默认大小/文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34299307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com