从子窗体更改父窗体中的属性的正确方法是什么? [英] What is the correct way to change properties in a parent form from a child form?

查看:61
本文介绍了从子窗体更改父窗体中的属性的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道我做这件事的方式是否正确。我有两个窗体,一个父窗体和一个子窗体("选项"对话框)。要从子窗体更改父窗体中的属性,我使用如下代码:

// 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个控件组成的数组似乎很愚蠢。这是正确的方法还是有更简单的方法?

推荐答案

根本不适合更改父窗体中的属性。相反,您的子窗体应该引发父窗体侦听的事件,并相应地更改其自身的值。

从子窗体操作父窗体会创建双向耦合-父窗体拥有子窗体,但子窗体也对父窗体有密切的了解和依赖关系。冒泡是这个问题的既定解决方案,因为它允许信息向上流动("冒泡"),同时避免任何严格的耦合。

这里是事件的最基本示例。它不包括在事件中传递特定信息(这可能是您需要的),但涵盖了概念。

在您的子窗体中:

//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
}
正如我上面所说的,您可能需要在事件中传递一些特定信息。我们有几种方法可以做到这一点,但最简单的方法是创建您自己的EventArgs类和您自己的委托。看起来您需要指定是否将某个值设置为true或false,因此让我们使用该值:

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;

我们传递自定义EventArgs对象:

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;
}

这篇关于从子窗体更改父窗体中的属性的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆