【发布时间】:2016-08-16 15:36:22
【问题描述】:
使用 SetPropertyBulk 方法将 CheckBox 的高度设置为 16,其实际高度最终会高出 1 个像素 (17)。
相关方法:
public IEnumerable<Control> GetAllControls(Control parentControl, Type type = null)
{
var controls = parentControl.Controls.Cast<Control>();
if (type != null)
{
return
controls.SelectMany(ctrl => GetAllControls(ctrl, type))
.Concat(controls)
.Where(c => c.GetType() == type);
}
return controls.SelectMany(ctrl => GetAllControls(ctrl)).Concat(controls);
}
public void SetPropertyBulk(string propertyS, object val, Type t = null,
Control parentControl = null)
{
Control parent = parentControl ?? _f;
foreach (Control c in GetAllControls(parent, t))
{
PropertyInfo p;
try
{
p = c.GetType().GetProperty(propertyS,
BindingFlags.Public
| BindingFlags.Instance
| BindingFlags.FlattenHierarchy);
}
catch (AmbiguousMatchException)
{
p = c.GetType().GetProperty(propertyS,
BindingFlags.Public
| BindingFlags.Instance
| BindingFlags.DeclaredOnly);
Debug.Print($"Ambiguous match for property {propertyS} " +
$"in control {c}");
}
if (p != null && p.CanWrite)
{
try
{
p.SetValue(c, val, null);
Debug.Print($"================\n" +
$"Set property\n" +
$"Type: {c}\n" +
$"Property: {p.Name}\n" +
$"Value: {val}\n" +
$"Check: {p.GetValue(c)}");
}
catch (ArgumentException)
{
Debug.Print(
$"The given value {val} is not valid for the " +
$"given property {propertyS} in control {c}.");
}
}
else
{
Debug.Print($"The given property {propertyS} does not " +
$"exist for control {c}.");
}
}
}
public void SetPropertyBulk(string propertyS, object val, ICollection<Type> t,
Control parentControl = null)
{
foreach (Type type in t)
{
SetPropertyBulk(propertyS, val, type);
}
}
我正在调用表单加载事件中的方法,如下所示:
const int cHeight = 16;
SetPropertyBulk("Height", cHeight,
new List<Type>
{
typeof(Label),
typeof(CheckBox),
typeof(TextBox),
typeof(NumericUpDown)
});
SetPropertyBulk("MinimumSize", new Size(0, cHeight),
new List<Type> {typeof(Label), typeof(CheckBox)});
SetPropertyBulk("AutoSize", true,
new List<Type> {typeof(Label), typeof(CheckBox)});
我正在检查 height 属性的值,如下所示:
Debug.Print($"Check Top: {GenChkScreen.Top}");
Debug.Print($"Check Bottom: {GenChkScreen.Bottom}");
Debug.Print($"Check Height: {GenChkScreen.Height}");
然后它返回:
检查顶部:15
检查底部:32
检查高度:17
我在SetPropertyBulk 中也有一个Debug.Print,它对于 CheckBox 返回:
=================
设置属性
类型:System.Windows.Forms.CheckBox,CheckState:0
属性:高度
价值:16
检查:16
前一个调试输出返回高度17,而后一个调试输出PropertyInfo.GetValue()返回高度16。通过将CheckBox的BackColor属性设置为与表单不同的颜色并计算像素,实际CheckBox 的大小为 17。
为什么高度没有设置为 16?为什么PropertyInfo.GetValue() 返回错误的高度(或者,我不知道,高度在SetPropertyBulk 中设置后再次更改。)
【问题讨论】:
-
如果你删除了
AutoSize,它的大小还会改变吗?否则我唯一的另一个想法是有一个内置的限制,也许检查源? -
@cjb110 是的,将
AutoSize设置为false确实允许将高度设置为16。这让我意识到我的错误,即我从未将MaximumSize设置为16好吧,为了防止AutoSize过去。 -
将您的问题标记为已回答的正确方法是接受一个答案(通过使用相应答案旁边的复选标记),而不是编辑您的问题并在其中任何一个中添加“已解决”字样标题或正文。请尊重本网站的适当约定。
-
@Damien_The_Unbeliever cjb110 发表了评论,因此我无法将其标记为答案(即使评论并没有直接回答问题。)我无法将自己的答案标记为已解决,因为我有要等两天。我的想法是:为什么要浪费人们的时间让他们点击这个问题只是为了它已经解决了?