我正在为一个大型项目编写一个自定义的DataGridView对象,以分发给一群开发人员,以使我们的应用程序部分看起来一致。
我想为DataGridView的许多属性设置默认值,我可以像这样设置它们中的许多属性:
<System.ComponentModel.Browsable(True), System.ComponentModel.DefaultValue(DataGridViewAutoSizeColumnsMode.Fill)>_
Public Overloads Property AutoSizeColumnsMode() As DataGridViewAutoSizeColumnMode
Get
Return MyBase.AutoSizeColumnsMode
End Get
Set(ByVal value As DataGridViewAutoSizeColumnMode)
MyBase.AutoSizeColumnsMode = value
End Set
End Property这些属性用它们的默认值重载就可以了。当我开始尝试创建默认的单元格样式时,我遇到了这个问题。因为DataGridViewCellStyle是一个类,所以我不能让它成为一个常量。我已经尝试在类构造函数中将所有设置更改为我想要的设置,效果很好,只是在应用程序运行时,在设计器属性中所做的更改就会被重新设置。因此,将更改放入构造函数是行不通的。
有没有其他地方可以让我只在控件第一次放到设计器上时才运行代码?或任何其他设置默认值的方法?
发布于 2010-02-11 05:18:45
实际上,我考虑了一段时间,发现了一个更简单的解决问题的方法。这并不适用于所有情况,因为它依赖于这样一个事实,即使用自定义组件的人可能永远不会想要将整个CellStyle恢复为windows默认值。最后,我在构造函数中将新的CellStyle与当前的样式进行了比较,只有当它们匹配时才设置样式。这样,它不会覆盖更改,但会在第一次设置它。
Public Class CustomDataGridView
Inherits System.Windows.Forms.DataGridView
Private RowStyle As New DataGridViewCellStyle
Public Sub New()
RowStyle.BackColor = Color.FromArgb(223, 220, 200)
RowStyle.Font = New Font("Arial", 12.75, FontStyle.Bold, GraphicsUnit.Point)
RowStyle.ForeColor = Color.Black
RowStyle.SelectionBackColor = Color.FromArgb(94, 136, 161)
If MyBase.RowsDefaultCellStyle.ToString = (New DataGridViewCellStyle).ToString Then
MyBase.RowsDefaultCellStyle = RowStyle
End If
End Sub
End Class只是为了说明,仅仅因为你有一把金锤子,并不意味着每个问题都是一颗钉子。
发布于 2010-11-09 18:06:59
我也遇到了这个问题。我的解决方案解决了DefaultValue参数必须是编译时常量的要求。我想,在类构造函数(在C#中由静态构造函数定义,在VB中由共享构造函数定义)中设置值还不够吗?
在我的例子中,这似乎是一个很好的变通方法,尽管它可能会在某些情况下中断,因为它实际上并不存在于元数据中,直到类构造函数在加载类时被调用,但对于应该被接受的设计器属性。因为DefaultValueAttribute.SetValue是受保护的,所以我必须定义一个派生类,使其成为公共类。
这在设计器中工作得很好,它可以识别该值何时与默认值相同,并在可能的情况下从生成的代码中省略它,并且只生成与默认值不同的值。
这是C#中的代码,这在VB中也应该可以工作,但我不太熟悉它的语法,所以我必须把它留给你。
public partial class HighlightGrid : DataGridView
{
// Class constructor
static MethodGrid()
{
// Get HighlightStyle attribute handle
DefaultValueSettableAttribute attr =
TypeDescriptor.GetProperties(typeof(HighlightGrid))["HighlightStyle"]
.Attributes[typeof(DefaultValueSettableAttribute)]
as DefaultValueSettableAttribute;
// Set default highlight style
DataGridViewCellStyle style = new DataGridViewCellStyle();
style.BackColor = Color.Chartreuse;
attr.SetValue(style);
}
[DefaultValueSettable, Description("Cell style of highlighted cells")]
public DataGridViewCellStyle HighlightStyle
{
get { return this.highlightStyle; }
set { this.highlightStyle = value; }
}
// ...
}
// Normally the value of DefaultValueAttribute can't be changed and has
// to be a compile-time constant. This derived class allows setting the
// value in the class constructor for example.
public class DefaultValueSettableAttribute : DefaultValueAttribute
{
public DefaultValueSettableAttribute() : base(new object()) { }
public new void SetValue(Object value) { base.SetValue(value); }
}https://stackoverflow.com/questions/2239684
复制相似问题