[英]What is best practice with regards to communicating between a user control and parent page?
I've been tasked with refactoring a mess of a page, and I would like to refactor it in the best way possible. 我的任务是重构一团糟的页面,我想以最好的方式重构它。 The layout page is 600+ lines, and the code file is nearly 1400. I would like to separate different modules of the page into user controls, but those modules are receiving information, unsurprisingly, from the page they're on. 布局页面有600余行,代码文件也接近1400行。我想将页面的不同模块分成用户控件,但是这些模块正在接收来自他们所在页面的信息,这不足为奇。 For a short sample: 对于简短的示例:
private void btnGetItem_Click(object sender, System.EventArgs e)
{
product = Products.getAllItemInformation(txtItemNbr.Text);
txtDescription.Text = product.getDesc();
setListBoxSelected(listMarketingSegment, product.getMarketingSegment());
}
private void setListBoxSelected(ListBox box, string pipeDelimitedStr)
{
pipeDelimitedStr = pipeDelimitedStr.Replace((char)253, '|');
pipeDelimitedStr = pipeDelimitedStr.Trim('|');
pipeDelimitedStr = "|" + pipeDelimitedStr + "|";
foreach (ListItem item in box.Items)
{
if (pipeDelimitedStr.IndexOf("|" + item.Value + "|") >= 0 && item.Value.Trim().Length > 0)
{
item.Selected = true;
}
}
}
How can I allow this functionality? 如何允许此功能? A user control needs to be able to access that same product from the parent page, but I'm not sure what the best practice is for that to happen. 用户控件需要能够从父页面访问同一产品,但是我不确定这是什么最佳实践。
I read http://www.codeproject.com/Articles/8797/Mastering-Page-UserControl-Communication , but I'm not sure how to relate it to my situation. 我阅读了http://www.codeproject.com/Articles/8797/Mastering-Page-UserControl-Communication ,但是我不确定如何将其与我的情况联系起来。 Do I create an interface? 是否创建界面? Create event driven communication? 创建事件驱动的通信? If so, how do I pass the product information to that user control? 如果是这样,我如何将产品信息传递给该用户控件?
You can do it MVVM way. 您可以通过MVVM方式进行操作。 Create a ViewModel, inherit from INotifyPropertyChanged, define properties for you data. 创建一个ViewModel,从INotifyPropertyChanged继承,为您的数据定义属性。 Set datacontext of your parent page and usercontrol as your ViewModel and keep on updating properties. 将父页面和用户控件的datacontext设置为ViewModel并继续更新属性。 Now on usercontrol and on parent page you can access data using these properties. 现在,在用户控件和父页面上,您可以使用这些属性访问数据。 Here is one example . 这是一个例子 。 you will find many more links/example over the net to implement things MVVM way. 您将在网上找到更多实现MVVM方式的链接/示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.