问题描述
我创建了一个组件,我希望能够在组件托盘中编辑时更改其名称.我已经为 name 属性添加了一个 Designer 操作,但现在我卡住了.
I've created a component whose name I'd like to be able to change while editing in the component tray.I've added a Designer action for a name property, but now I'm stuck.
查看属性网格,可以看到 name 属性被括号括起来,表明它不是常规属性.
Looking at the property grid, I can see that the name property is parenthesised, indicating that it's not a regular property.
这可能吗?
推荐答案
您可以在设计时使用 Component.Site.Name
更改 Component
的名称.您应该将代码放在 try/catch 块中以处理名称重复时的异常.
You can change the name of a Component
at design-time using Component.Site.Name
. You should put the code in a try/catch block to handle exception when the name is duplicate.
代码:
当您为组件实现设计器时,在设计时更改组件名称的 man 代码是:
When you implement a designer for your component, the man code for change the name of component at design time is:
this.Component.Site.Name = "SomeName";
这是一个组件和一个组件设计器的完整实现.组件设计器有一个动词,当您右键单击组件时可以访问它,也可以从命令托盘中的属性网格访问它.当您单击Rename
命令时,它会将组件的名称设置为SomeName
.如果存在同名的组件,它还会显示错误消息.在更真实的示例中,您可以覆盖 ActionLists
以让用户自己输入新名称.
Here is a full implementation of a component and a component designer. The component designer has a verb that is accessible when you right click on the component, also it's accessible from property grid in commands tray. When you click on Rename
command, it sets the name of component to SomeName
. It also shows an error message if there is a component with the same name. In a more realistic sample, you can override ActionLists
to let the user enter a new name itself.
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Windows.Forms.Design;
[Designer(typeof(MyComponentDesigner))]
public class MyComponent : Component
{
public string SomeProperty { get; set; }
}
public class MyComponentDesigner : ComponentDesigner
{
DesignerVerbCollection verbs;
public MyComponentDesigner() : base() { }
public override DesignerVerbCollection Verbs
{
get
{
if (verbs == null)
{
verbs = new DesignerVerbCollection();
verbs.Add(new DesignerVerb("Rename", (s, e) =>
{
try
{
this.Component.Site.Name = "SomeName";
this.RaiseComponentChanged(null, null, null);
}
catch (Exception ex)
{
var svc = ((IUIService)this.GetService(typeof(IUIService)));
svc.ShowError(ex);
}
}));
}
return verbs;
}
}
}
这篇关于是否可以在 WinForms .Net 的组件设计器中更改组件名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!