gpt4 book ai didi

c# - 将字符串传递给标签的正确方法是什么?

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

我有一个 winform,我想将一系列字符串传递给一系列标签。

这是代码:

   public partial class CourierDeliveringEnemyReport : Form
{
public static string Label1 { get; set; }
public static string Label2 { get; set; }
public static string Label3 { get; set; }
public static string Label4 { get; set; }
public static string Label5 { get; set; }
public string Label6 { get; set; }

public CourierDeliveringEnemyReport()
{

InitializeComponent();

label1.Text = Label1;
label2.Text = Label2;
label3.Text = Label3;
label4.Text = Label4;
label5.Text = Label5;
label6.Text = "This is a test!";
}

在此处设置值:

CourierDeliveringEnemyReport dlg = new CourierDeliveringEnemyReport();
CourierDeliveringEnemyReport.Label1 = "Report from " + BlueArmy[GameEventList[i].ObservingUnit].Name; ;
string temp2 = "Enemy unit (" + RedArmy[GameEventList[i].Unit].Name + ") observed!";
CourierDeliveringEnemyReport.Label2 = temp2;
string temp3 = "This intelligence is " + RedArmy[GameEventList[i].Unit].LastTimeObservedByEnemy + " minutes old.";
CourierDeliveringEnemyReport.Label3 = temp3;

使用调试器,我可以确认正在传递有效的字符串。例如,Label1 包含字符串“Report from...”。

问题是标签不采用除 label6(测试用例)之外的字符串值。

我做错了什么?

谢谢!

最佳答案

您没有绑定(bind)标签到变量,您只设置了一次。似乎您希望标签在相关 LabelX 字符串更新时更新,但这只有在有某种通知时才会发生。

例如,您的表单可以实现 INotifyPropertyChanged并且您的 Label 属性可以在更改时发出通知。

public partial class CourierDeliveringEnemyReport : Form, INotifyPropertyChanged

然后可以类似这样实现

private string _label1;

public string Label1
{
get { return _label1; }
set
{
if(_label1 == value) return;

_label1 = value;
OnPropertyChanged("Label1");
}
}

//implement the INotifyPropertyChanged interface
public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged(string prop)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}

由于这是 WinForms,因此没有用于添加绑定(bind)的 XAML 标记,因此您可以在代码后面使用 Binding 进行添加.

public CourierDeliveringEnemyReport()
{

InitializeComponent();
//"Text" is the property on the control to get/set (i.e. Label1.Text)
//this is the datasource
//"Label1" is the property in our code
label1.DataBindings.Add(new Binding("Text", this, "Label1"))

//add bindings for other labels
}

(代码未经测试,但应该给出一个想法)

关于c# - 将字符串传递给标签的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38463638/

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