【发布时间】:2012-01-05 07:24:01
【问题描述】:
如何判断 WinForms Control 的 属性 是否为“默认”值?
注意:在设计时,当属性变为粗体时,您可以判断该属性不再是“默认”。
这是一个标签字体的示例(在设计时),它是 “默认”值(这意味着它从其父级获取其值):
(如果父字体改变,这个标签的字体也会改变)
这里一个标签的字体已经改变,不再是默认值:
(如果父字体改变,这个标签的字体不会改变)
细心的观察者会注意到,同一面板上的这两个标签是“相同的字体”;除了一个是默认而另一个不是。
注意:我需要在 runtime 知道某个属性是否不是“默认”值。 (有人可能会作弊说,“查看属性窗口。如果属性是粗体,你就知道它不再是默认值了”。)
注意:注意,我的问题不仅限于标签字体 - 这只是我使用的示例。我可能想知道它是否仍然是默认值的其他属性示例:
ForeColorBackColorToolStrip.ImageScalingSizeSplitContainer.FixedPanel
我陷入疯狂的尝试
我将把这些失败的随机乱码呕吐尝试留在这里:
internal static Boolean GetIsPropertyDefault(object o, string propertyName)
{
return false;
/* Debug.WriteLine(String.Format("GetIsPropertyDefault: {0}.{1} = {2}", o, propertyName, TypeDescriptor.GetProperties(o)[propertyName].GetValue(o)));
// Gets the attributes for the property.
AttributeCollection attributes = TypeDescriptor.GetProperties(o)[propertyName].Attributes;
DefaultValueAttribute myAttribute = (DefaultValueAttribute)attributes[typeof(DefaultValueAttribute)];
Debug.WriteLine(String.Format("The default value is: {0}", myAttribute));
if (myAttribute == null)
return true;
return (TypeDescriptor.GetProperties(o)[propertyName].GetValue(o) == myAttribute.Value);
*/
// return (myAttribute.Value == null);
// Console.WriteLine("The default value is: " + myAttribute.Value.ToString());
/* System.Reflection.PropertyInfo pi;
try
{
//pi = o.GetType().GetProperty(propertyName).GetCustomAttributes(typeof(DefaultAttribute), false).
}
catch
{
return true;
}
if (pi == null)
return true;
System.Diagnostics.Trace.TraceInformation(pi.Attributes.ToString());
*/
// return false;
/* foreach (Attribute attr in pi.Attributes)
{
if (attr is System.ComponentModel.DefaultValueAttribute)
{
System.ComponentModel.DefaultValueAttribute dv = (System.ComponentModel.DefaultValueAttribute)attr;
}
}
*/
}
【问题讨论】:
-
看看这个类似的 Q - 它有一些好主意:stackoverflow.com/questions/271904/…。我正在研究 DefaultValueAttribute:msdn.microsoft.com/en-us/library/…
标签: winforms properties controls