我有一个班级,班上有一些对象。现在,我想选择一个对象并显示在表单上。同时,我要编辑选定的一个。我使用了INotifyPropertyChanged并能够显示所选对象。不,我有些麻烦。
1-当我使用myDislayingObject = myObject1
时不起作用。所以我必须使用
myDislayingObject.property1 = myObject1.property1
myDislayingObject.property2 = myObject1.property2
我想复制具有所有属性的对象,包括事件等。
2-我正在文本框上显示属性。当我编辑文本框时,我不会更改源对象。
namespace DisplayObjectsInForm
{
public partial class Form1 : Form
{
public Araba Araba1 = new Araba();
public Araba Araba2 = new Araba();
public Araba Araba3 = new Araba();
public Araba DisplayingAraba = new Araba();
public Form1()
{
InitializeComponent();
Araba1.sName = "Araba1";
Araba1.sColor = "Kirmizi";
Araba1.nModel = 1999;
Araba2.sName = "Araba2";
Araba2.sColor = "Mavi";
Araba2.nModel = 2005;
Araba3.sName = "Araba3";
Araba3.sColor = "Gri";
Araba3.nModel = 2018;
textBox1.DataBindings.Add("Text", DisplayingAraba, "sName");
textBox2.DataBindings.Add("Text", DisplayingAraba, "sColor");
textBox3.DataBindings.Add("Text", DisplayingAraba, "nModel");
}
public class Araba : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
public string sNameInternal;
public string sName
{
get
{
return sNameInternal;
}
set
{
if (sNameInternal != value)
{
sNameInternal = value;
NotifyPropertyChanged("sName");
}
}
}
public string sColorInternal;
public string sColor
{
get
{
return sColorInternal;
}
set
{
if (sColorInternal != value)
{
sColorInternal = value;
NotifyPropertyChanged("sColor");
}
}
}
public int nModelInternal;
public int nModel
{
get
{
return nModelInternal;
}
set
{
if (nModelInternal != value)
{
nModelInternal = value;
NotifyPropertyChanged("nModel");
}
}
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
switch(comboBox1.SelectedIndex)
{
case 0:
{
DisplayingAraba.sName = Araba1.sName;
DisplayingAraba.sColor = Araba1.sColor;
DisplayingAraba.nModel = Araba1.nModel;
break;
}
case 1:
{
DisplayingAraba.sName = Araba2.sName;
DisplayingAraba.sColor = Araba2.sColor;
DisplayingAraba.nModel = Araba2.nModel;
break;
}
case 2:
{
//Not working
DisplayingAraba = Araba3;
break;
}
}
}
}
}
答案 0 :(得分:0)
该操作无效,因为您最初将DisplayAraba
设置为新的Araba
。请尝试以下操作
namespace DisplayObjectsInForm
{
public partial class Form1 : Form
{
public Araba Araba1 = new Araba();
public Araba Araba2 = new Araba();
public Araba Araba3 = new Araba();
public Araba DisplayingAraba;//Remove the initialization from here.
public Form1()
{
InitializeComponent();
DisplayingAraba = new Araba(); //Add this line here
Araba1.sName = "Araba1";
Araba1.sColor = "Kirmizi";
Araba1.nModel = 1999;
Araba2.sName = "Araba2";
Araba2.sColor = "Mavi";
Araba2.nModel = 2005;
Araba3.sName = "Araba3";
Araba3.sColor = "Gri";
Araba3.nModel = 2018;