开发者

C# passing data between classes

Just wondering how people would go about this. Say I have one class that creates and populates a Treeview which is then added to a Winform.

I have another class that is dependent upon data within the Treeview. So for example, when a user clicks on a specific node in the Treeview, class b needs that information that the node holds so that it can perform some calculation and display the result.

Would it better practise to simply pass a reference to the Treeview to the second class, or just the data that it needs? Or would it be okay to set the Treeview as sta开发者_C百科tic and use events so that the new class can access the treeview directly when a node is clicked on?

Thanks.


I would raise an event in the class that holds the treeview. That is, define a delegate and an event your class has. Then the depending class can subscribe to that event and act on the data included in the event. As I understand your question the depending class doesn't need to do anything with the treeview and should therefor not know about the treeview.

public delegate void YouControlHandler(int relevantData1, string relevantData2);
public class ClassContainingTreeView
{
    public event YouControlHandler TreeViewClickedEvent;
    public void OnTreeViewClicked(object sender, EventArgs)
    {
        // Handle request locally first and extract relevantData1/2
        if(TreeViewClickedEvent != null)
            TreeViewClickedEvent(relevantData1, relevantData2);
    }
}

public class DependingClass
{
     ClassContainingTreeView yourObject = new ClassContainingTreeView();

     public DependingClass()
     {
         yourObject.TreeViewClickedEvent += new YouControlHandler(EventHandler);
     }

     protected void EventHandler(int relevantData1, string relevantData2)
     {
             // Handle event
     }
}


Just pass the data.

You do not want a class to be tightly coupled to a UI control.


As an aside, why do you think you need to make the TreeView static in order to consume events from it?

You can subscribe to an event from objects that are not static.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜