gpt4 book ai didi

c# - 自定义标签不显示文本字符串

转载 作者:太空宇宙 更新时间:2023-11-03 17:26:45 25 4
gpt4 key购买 nike

我需要制作自己的标签来保存一些值,这与显示给用户的值不同

public class LabelBean : Label {
private string value;

public LabelBean(string text = "", string value = ""): base() {
base.Text = text;
this.value = value;
}

public string Value {
get { return value; }
set { this.value = value; }
}
}

但现在我在表单构造函数中用我的类替换控件

this.lbAttributeType = new LabelBean();

稍后在创建表单之后,但在显示之前我通过 setter 设置了文本

(this.lbAttributeType as LabelBean).Value = value;
this.lbAttributeType.Text = Transform(value);

但在表格中我总是使用“label1”文本...这有什么问题吗?谢谢

更新

我在这里添加解决方案是为了更容易找到:

public class MyLabel : Label {

public MyLabel()
: base() {
}

public string Value {
set {
this.Text = value;
}
}
}

以及带有 Widnows.Forms.Label label1 控件的表单

public partial class Form1 : Form {

public Form1() {
InitializeComponent();
this.Controls.Remove(this.label1);
this.label1 = new MyLabel();
this.Controls.Add(this.label1);
(this.label1 as MyLabel).Value = "oh";
}
}

错误在 Controls.RemoveControls.Add 中,感谢大家花时间:)

最佳答案

我的猜测是因为,由于您是在构造函数中完成工作,因此由设计器自动生成的 InitializeComponent 代码正在覆盖控件实例,因为它很可能在您的初始化之后被调用.

如果该类是项目的一部分,您将在工具箱中找到它;这意味着您可以简单地将新控件拖放到窗体上以代替现有控件 - 这是您应该做的。

这确保设计器生成的属性属于您的 LabelBean 类型,而不仅仅是 Label

此外 - 您应该考虑更改您的 Value setter,如 WoLfulus 所示(+1)

更新

作为对您对 WoLfulus 回答的评论的回应 - 这里有几个备选方案:

1) 如果表单是这里的“聪明”位 - 考虑只在其中编写一个辅助方法,并通过它设置标签的值,利用 Tag 属性:

public void SetLabelBean(Label target, string value)
{
Label.Tag = value;
Label.Text = Transform(value);
}

public string GetLabelBean(Label target)
{
return target.Tag as string;
}

2) 继续使用您的子类 LabelBean 类型(通过设计器添加它,正如我已经提到的那样)——但是使用一个抽象来让它访问表单的 Transform 方法:

public interface ITransformProvider
{
string Transform(string);
}

让你的表单类实现这个接口(interface),使用你回避的 Transform 方法。

现在,在您的 LabelBean 类中:

public ITransformProvider Transformer
{
get{
//searches up the control hierarchy to find the first ITransformProvider.
//should be the form, but also allows you to use your own container controls
//to change within the form. The algorithm could be improved by caching the
//result, invalidating it if the control is moved to another container of course.
var parent = Parent;
ITransformProvider provider = parent as ITransformProvider;
while(provider == null){
parent = parent.Parent;
provider = parent as ITransformProvider;
}
return provider;
}
}

然后,最后,使用 WoLfulus 的代码,但稍作更改,您可以这样做:

public string Value          
{
get
{
return value;
}
set
{
this.value = value;
var transformer = Transformer;
if(transformer != null) this.Text = transformer.Transform(value);
}
}

我认为,该答案解决了您的问题。

关于c# - 自定义标签不显示文本字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8851572/

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