English 中文(简体)
从儿童形式改变母体形式的特性的正确方式是什么?
原标题:What is the correct way to change properties in a parent form from a child form?
  • 时间:2009-08-15 23:20:09
  •  标签:

我很想知道,我是否这样做是正确的。 我有两种家长形式和儿童形式(选择方言)。 从我的子女形式上改变我父母的财产,我使用这样的法典:

// Create an array of all rich textboxes on the parent form.
var controls = this.Owner.Controls.OfType<RichTextBox>();

foreach (var item in controls) {
    if (chkDetectUrls.Checked)
        ((RichTextBox)item).DetectUrls = true;
    else
        ((RichTextBox)item).DetectUrls = false;
}

我的表格只有一个RichTextBox。 似乎不得不通过一系列1项控制 lo。 这样做的正确方式是不是容易的?

最佳回答

根本不宜改变母体形式的财产。 相反,你的子女形式应当引起父母所倾听的活动,并相应改变其自身的价值。

选择孩子的母体形式会产生双向的 coup合——母体形式拥有孩子,但儿童也非常了解和依赖父母的形式。 贿赂是解决这一问题的既定办法,因为它使信息能够向上流动(泡沫),同时避免任何严格的政变。

这里是事件的最基本例子。 它不包括在该事件中传递具体信息(这是你可能需要的),而是涵盖这一概念。

以儿童为形式:

//the event
public event EventHandler SomethingHappened;

protected virtual void OnSomethingHappened(EventArgs e)
{
    //make sure we have someone subscribed to our event before we try to raise it
    if(this.SomethingHappened != null)
    {
        this.SomethingHappened(this, e);
    }
}

private void SomeMethod()
{
    //call our method when we want to raise the event
    OnSomethingHappened(EventArgs.Empty);
}

并以你的母体形式:

void OnInit(EventArgs e)
{
    //attach a handler to the event
    myChildControl.SomethingHappened += new EventHandler(HandleSomethingHappened);
}

//gets called when the control raises its event
private void HandleSomethingHappened(object sender, EventArgs e)
{
    //set the properties here
}

正如我前面说过的那样,你可能需要在你的活动中传递一些具体的信息。 我们可以采取几种方式,但最简单的办法是创建你自己的活动协会和你自己的代表。 它希望你具体说明某种价值是否真的或假的,以便利用:

public class BooleanValueChangedEventArgs : EventArgs
{
    public bool NewValue;

    public BooleanValueChangedEventArgs(bool value)
        : base()
    {
        this.NewValue = value;
    }
}

public delegate void HandleBooleanValueChange(object sender, BooleanValueChangedEventArgs e);

我们可以改变我们利用这些新签名的活动:

public event HandleBooleanValueChange SomethingHappened;

我们通过了我们的习俗活动。

bool checked = //get value
OnSomethingHappened(new BooleanValueChangedEventArgs(checked));

因此,我们改变了在母公司处理事件的做法:

void OnInit(EventArgs e)
{
    //attach a handler to the event
    myChildControl.SomethingHappened += new HandleBooleanValueChange(HandleSomethingHappened);
}

//gets called when the control raises its event
private void HandleSomethingHappened(object sender, BooleanValueChangedEventArgs e)
{
    //set the properties here
    bool value = e.NewValue;
}
问题回答

暂无回答




相关问题
热门标签