2014-10-17 119 views
1

我有一个表格,其中Property名为Car这是一个有几个属性的类。C#窗体 - 属性更改

根据一些用户的行为是财产将被设置为当前显示。

所以我想知道何时该属性被分配或设置为空。

我知道了INotifyPropertyChanged的,但在我的情况我不知道,如果因为我不希望我的监视性能Car改变,但Car财产本身是适用的。

任何想法如何实现这一点?

在此先感谢

+3

请添加相关代码的形式和'car'类。你应该可以将'INotifyPropertyChanged'添加到表单中。 – Rhumborl 2014-10-17 11:01:59

+0

这是正确的,它并没有跨越我的脑海:)谢谢 – user2779312 2014-10-17 11:06:39

+0

我认为实施INotifiyPropertyChanged是一个好主意。但如果由于某种原因你不想这么做(这比稍微有点麻烦),你可以坚持正常的Forms范例,实现一个普通的旧的“CarChanged”事件。然后,需要知道属性值何时发生更改的代码才可以订阅该特定事件(INotifyPropertyChanged更具通用性,这可能很好,但这也意味着订户会收到有关_all_属性更改的通知,而不仅仅是他们关心的关于)。 – 2014-10-17 18:29:02

回答

0

如果你创建你的类真正的财产,那么你应该有一个getter和setter。 您可以在表格setter方法直接添加代码取决于其“车”采取行动的值设置为:

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    // Define the Car class 
    public class Car 
    { 
     public string Name = string.Empty; 
    } 

    // private variable to hold the current Car value 
    private Car _car = null; 

    // Public form property that you can run code when either the get or set is called 
    public Car car 
    { 
     get 
     { 
      return _car; 
     } 
     set 
     { 
      _car = value; 

      if (_car == null) 
       MessageBox.Show(this, "Run code here when car is set to null", "Car is set to null"); 
      else 
       MessageBox.Show(this, "Run code here: the cars name is: '" + _car.Name + "'", "Car is set to a value"); 
     } 
    } 
    private void SomeFunction() 
    { 
     Car MyCar = new Car(); 
     MyCar.Name = "HotRod"; 

     // This will fire the car setter property 
     this.car = MyCar; 
    } 
}