C# .Net UserControl 的设计问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-01 08:50:51  来源:igfitidea点击:

Design problems with .Net UserControl

提问by Matt Nelson

I have created a UserControl that has a ListViewin it. The ListView is publicly accessible though a property. When I put the UserControl in a form and try to design the ListViewthough the property, the ListViewstays that way until I compile again and it reverts back to the default state.

我创建了一个 UserControl,其中有一个ListView。ListView 可通过属性公开访问。当我将 UserControl 放入表单并尝试设计该ListView属性时,该属性将ListView保持这种状态,直到我再次编译并恢复为默认状态。

How do I get my design changes to stick for the ListView?

如何让我的设计更改坚持下去ListView

采纳答案by Fredrik Kalseth

You need to decorate the ListView property with the DesignerSerializationVisibility attribute, like so:

您需要使用 DesignerSerializationVisibility 属性装饰 ListView 属性,如下所示:

[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public ListView MyListView { get { return this.listView1; } }

This tells the designer's code generator to output code for it.

这告诉设计器的代码生成器为其输出代码。

回答by Matt Hamilton

Just so I'm clear, you've done something like this, right?

我很清楚,你做过这样的事情,对吧?

public ListView MyListView { get { return this.listView1; } }

So then you are accessing (at design time) the MyListView property on your UserControl?

那么您正在访问(在设计时)UserControl 上的 MyListView 属性?

I think if you want proper design-time support you're better off changing the "Modifier" property on the ListView itself (back on the original UserControl) to Public - that way you can modify the ListView directly on instances of the UserControl. I've had success doing that anyway.

我认为如果您想要适当的设计时支持,最好将 ListView 本身(回到原始 UserControl)上的“Modifier”属性更改为 Public - 这样您就可以直接在 UserControl 的实例上修改 ListView。无论如何,我已经成功地做到了这一点。

回答by Rob Cooper

Fredrikis right, basically, when you need to enable the designer to persist the property to page so it can be instantiated at run time. There is only one way to do this, and that is to write its values to the ASPX page, which is then picked up by the runtime.

Fredrik是对的,基本上,当您需要让设计器将属性持久化到页面以便它可以在运行时实例化时。只有一种方法可以做到这一点,那就是将其值写入 ASPX 页面,然后由运行时获取。

Otherwise, the control will simply revert to its default state each and every time.

否则,控件每次都会简单地恢复到其默认状态。

Always keep in the back of your mind that the Page (and its contents) and the code are completely seperate in ASP.NET, they are hooked up at run time. This means that you dont get the nice code-behind designer support like you do in a WinForms app (where the form is an instance of an object).

永远记住,页面(及其内容)和代码在 ASP.NET 中是完全分开的,它们在运行时是连接在一起的。这意味着您无法像在 WinForms 应用程序(其中表单是对象的实例)中那样获得良好的代码隐藏设计器支持。