我有2種形式:表格A和表格B.我也有一個屬性字段類。通過物業變更價值
表單A包含我想在屬性發生更改時更改的標籤。表格B包含將改變屬性字段的代碼。
屬性類代碼:
public class Controller
{
private static string _customerID;
public static string customerID
{
get { return _customerID; }
set
{
_customerID = value;
if (_customerID != "")
{
FormA.ChangeMe();
}
}
}
}
形式B編碼:
private void something_Click(object sender, SomethingEventArgs e) {
Controller.customerID = "Cool";
}
形式A代碼:
public static void ChangeMe()
{
var frmA = new FormA();
MessageBox.Show("Test: " + Controller.customerID); //This works! Shows Cool
frmA.lb2Change.Text = Controller.customerID; //This kind of works..
MessageBox.Show("Test2: " + frmA.lb2Change.Text); //This shows the correct value. Shows Cool
}
的屬性字段值被傳遞(這是我從在MessageBox知道),但它不會更新表單標籤本身的值。爲什麼是這樣?我究竟做錯了什麼?我也相信有一個更好的替代方案來實現ChangeMe()方法的意圖實現 - 如果有的話,是否有任何建議?
如前所述,因爲你正在改變一個屬性值'frmA'的新實例,而不是已經存在的實例以及用戶實際使用的實例,用戶當然不會看到新值。請參閱https://stackoverflow.com/questions/32816542/c-sharp-cant-change-labels-and-button-properties-from-a-dialogbox查看堆棧溢出的許多類似問題之一,解決這個問題,常見錯誤。 –
就各種對象互動而言,您有各種各樣的選擇,所有這些選項都可以避免讓每個班級實際上需要知道關於另一個班級的任何具體內容。一種選擇是實現'INotifyPropertyChanged'並在需要通知的類中訂閱'PropertyChanged'。有關其他建議,請參閱https://stackoverflow.com/questions/1665533/communicate-between-two-windows-forms-in-c-sharp。同樣,堆棧溢出已經存在很多關於這些概念的問題。 –