在自定义控件中更改属性

时间:2014-04-19 04:56:20

标签: c# winforms c#-4.0

Link to Image

我已经创建了一个自定义控件,可以轻松地将行添加到TableLayoutPanel。在图像中看到的整行是控件的单个实例。我要实现一些功能,这样无论何时填写费率和数量,(完整)更改都应该在总计框中产生sum += (rate * quantity)

我在想的是OnPropertyChanged内的ProductControl.cs事件处理程序,它是自定义控件的类。我猜测我需要两个属性更改处理程序,一个用于Rate,另一个用于Quantity。每个都会检查其他字段是否为空,然后继续更新Product = Rate*Quantity值。

但是,我如何以主窗体访问这些处理程序?我需要将Total框更新为Total += (Rate*Quantity)Total += Product

ProductControl.cs的来源 - :

public partial class ProductControl : UserControl
{
        Dictionary<int, PairClass<string, double>> PC = new Dictionary<int, PairClass<string, double>>();
        public string Number
        {
            get
            {
                return ProdNo.Text;
            }
            set
            {
                ProdNo.Text = value;
            }
        }
        public ProductControl()
        {
            InitializeComponent();
        }

        public void SetMapping(Dictionary<int, PairClass<string, double>> map)
        {
            PC = map;
        }

        //This implements the functionality that whenever a Product Number is entered,
        //the Product Name and Rate appear automatically, by virtue of a mapping
        //between Product Number: Pair<Product Name, Rate>.
        private void ProdNoText_TextChanged(object sender, EventArgs e)
        {
            int x = 0;
            PairClass<string, double> pc = null;
            if (int.TryParse(ProdNoText.Text, out x))
            {
                PC.TryGetValue(x, out pc);
                if (pc != null)
                {
                    PNameText.Text = pc.First;
                    RateText.Text = pc.Second.ToString();
                }
            }
            else
            {
            }
        }
}

1 个答案:

答案 0 :(得分:1)

您可以为控件创建自定义事件,如下所示:

首先创建从ProductChangedEventArgs派生的类EventArgs,其中包含主表单处理产品更改所需的所有信息(让我们说Rate和{{ 1}})。此类只需要一个接受QuantityRate以及两个公共getter的构造函数。

然后,在你的课堂上:

Quantity

现在您需要做的就是在您希望从中发出事件的任何一点调用// This will be the signature of your event handlers public delegate void ChangedEventHandler(object sender, ProductChangedEventArgs e); // The event itself to which will be possible to bind callbacks functions // with the signature given by ChangedEventHandler public event ChangedEventHandler Changed; protected virtual void OnChanged(ProductChangedEventArgs e) { // This checks there's at least one callback bound to the event if (Changed != null){ // If there are callbacks, call all of them Changed(this, e); } }

例如,您将在所有产品属性的setter中调用它。

OnChanged

现在在主窗体中,您可以将回调绑定到private int _rate; public int Rate{ set{ if(_rate != value){ _rate = value; // Call the callbacks passing an EventArgs that reflects the actual state // of the product OnChanged(this, new ProductChangedEventArgs(_rate, ... )); } } } 事件,如下所示:

Changed