使用 c# 与另一个父对象通信或访问父对象 [英] communicate or access a parent from another using c#

查看:62
本文介绍了使用 c# 与另一个父对象通信或访问父对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎在一个简单的问题上遇到了很多麻烦.是的,我是 c# 的新手,但我尝试学习我能学到的东西,而不会跳到发布问题.在这种情况下,我只是认为我没有问正确的问题.

I seem to be have a great deal of trouble with a simple issue. Yes I'm new to c# but I try to learn what I can without jumping to post a question. In this case I just think I'm not asking the right question.

这里没有任何代码示例会有所帮助,因为我在谈论基础知识(实现).我还没有真正编码任何东西,只是使用可视化构建器来创建我的窗体和菜单.

No code samples will help here because I'm talking about the basics ( implementation ). I have not really coded anything yet, just use the visual builder to create my windows forms and menus.

我遇到的问题是当我选择一个菜单项(称之为:设置路径)时,我希望我的主表单上的列表视图从我在 form2 上点击确定时选择的路径加载.所以我做了一个简单的查找文件夹对话框,并将我的新路径存储在 form2 的文本框中.当我在那个 form2 上点击确定时,我希望我的 listview form1 填充.我知道如何完成所有这些,但我一生都无法从 form2 访问 form1,反之亦然.

The issue I'm having is when I select a menu item (call it: set paths ) I want that list view on my main form to load from the path selected when I hit ok on form2. So I did a simple find folder dialog and I have my new path stored on form2 in a text box. When I hit ok on that form2 I want my listview form1 to populate. I know how to do all of this but I can not for the life of me access form1 from form2 or vice versa.

我尝试创建回调函数,但我发现无法引用非静态变量...错误,因为我的 form1 是静态的,因此我无法创建任何非静态方法.我查看了 EventArgs,但对于这样一个常见的请求来说,这似乎有点过头了.

I tried making a call back function but I get that non-static variable cannot be referenced... error because my form1 is static, so I can't create any non static methods. I looked in to EventArgs but that just seems like an over kill for such a common request.

那么一般的做法是什么?

So what is the general way to do this?

推荐答案

就访问其他表单上的成员而言,Robert 的回答是正确的.但是,通常您应该将应用程序的状态(称为模型")与用户界面的状态(称为视图")分开.随着您的应用程序超出一两个交互,这变得非常重要.有几种关于如何将两者联系在一起的哲学或模式(例如谷歌模型-视图-控制器"(MVC)和模型-视图-视图模型"(MVVM)),如果你真的想正确地做到这一点,我会建议学习这些.我更喜欢 MVVM 方法,即使 Windows 窗体设计时考虑到了 WPF 应用程序,您也可以相当轻松地做到这一点.

Robert's answer is correct as far as accessing members on another form. However, in general you should be storing the state of your application (call it the "model") separately from the state of your user interface (call it the "view"). This becomes very important as your application grows beyond one or two interactions. There are several philosophies or patterns about how to tie the two together (Google "model-view-controller" (MVC) and "model-view-viewmodel" (MVVM) for example), and if you really want to do this correctly I would recommend learning about those. My preference is for the MVVM approach, and you can do it fairly easily with Windows Forms even though it was designed with WPF applications in mind.

在 .NET 中,您应该用来实现视图模型和视图之间的连接的基本代码是一个名为 INotifyPropertyChanged.您创建一个实现此接口的类,并在属性更改时发送通知,例如,对于您的路径属性,您将创建此类:

In .NET, the basic piece of code you should use to implement the connection between your viewmodel and your view is an interface called INotifyPropertyChanged. You create a class that implements this interface and sends notifications whenever a property changes, so for example for your path property you would create this class:

class ViewModel : INotifyPropertyChanged
{
    private string path;
    public string Path
    {
        get { return path; }
        set {
            if (value != path)
            {
                path = value;
                NotifyPropertyChanged();
            }
        }
    }

    // This event gets triggered whenever a property changes.
    public event PropertyChangedEventHandler PropertyChanged;

    // This will cause the event to actually be triggered. It automatically determines the name of the property that triggered it using the [CallerMemberName] attribute - just a bit of .NET 4.5 sweetness. :)
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

看起来工作量很大,但现在您可以在您的 form1 中创建一个新的ViewModel"实例,订阅该事件,然后将该实例传递给 form2.然后,只要用户选择不同的路径,form2 就会简单地更新 viewmodel 实例上的 Path 属性.

It may seem like a lot of work, but now in your form1 you can create a new "ViewModel" instance, subscribe to the event, and then pass the instance to form2. form2 then simply updates the Path property on the viewmodel instance whenever the user selects a different path.

因此,Form1 需要靠近顶部的此代码:

So, Form1 needs this code near the top:

private ViewModel viewmodel = new ViewModel();

这在 Form1 构造函数中:

And this goes in the Form1 constructor:

viewmodel.PropertyChanged += new EventHandler(OnPathChanged);

当您创建/显示 form2 时:

And when you create/show form2:

var form2 = new Form2(viewmodel); // Note, the viewmodel instance is being passed to the form2 constructor
form2.Show();

form2 构造函数然后存储自己对viewmodel"实例的引用,并在用户更改路径时设置 Path 属性.

The form2 constructor then stores its own reference to the "viewmodel" instance, and sets the Path property whenever the path is changed by the user.

private ViewModel viewmodel;

public Form2(ViewModel viewmodel)
{
    this.viewmodel = viewmodel;
    ... // Other stuff to set up your controls etc. goes here
}

private void PathChanged(object sender, EventArgs e) // This may be named differently in your code; it's the event handler that gets called when the path changes
{
    // This will automatically notify the event handler in Form1! It's super-elegant and flexible.
    this.viewmodel.Path = txtPath.Text; // Assuming you have a textbox called txtPath
}

最后是 Form1 中的事件处理程序:

And finally the event handler in Form1:

private void OnPathChanged(object sender, EventArgs e)
{
    var newPath = viewmodel.Path; // Get the updated path back from the viewmodel
    //TODO: Whatever you want to do when the path changes.
}

这是一个使用 Windows 窗体的非常好的 MVVM 介绍的链接,它使用两种形式,就像您在示例中使用的那样.MVVM(模型-视图-视图模型)模式对于 Windows 窗体应用程序,使用C#

Here's a link to a really good MVVM intro using Windows Forms, it uses two forms like you have in your example. MVVM (Model-View-ViewModel) Pattern For Windows Form Applications, using C#

这篇关于使用 c# 与另一个父对象通信或访问父对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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