Vb.net - 设置控件边距值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4837400/
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-09-09 15:15:11  来源:igfitidea点击:

Vb.net - Setting a controls margin value

vb.netwinformscontrolsmargin

提问by Kenny Bones

So, I'm adding a label programatically and I'm in need of altering the top margin a little bit to the value 8. I can't do that the obvious way, so what's wrong with my thinking?

所以,我正在以编程方式添加一个标签,我需要将顶部边距稍微更改为值 8。我不能以明显的方式做到这一点,所以我的想法有什么问题?

Dim LabelAdapter As New Label
LabelAdapter.text = "Adapter"
LabelAdapter.Margin.Top = 8

This gives me the error "Expression is a value and therefore cannot be the target of an assignment".

这给了我错误“表达式是一个值,因此不能成为赋值的目标”。

回答by Konrad Rudolph

Label.Marginreturns a Paddingobject.

Label.Margin返回一个Padding对象。

Since Paddingis a structure, it will actually return a copy. You are changing the Topvalue of that copy, not of the actual control's margin. Since that would have no noticeable effect, VB correctly prevents it.

由于Padding是一个结构,它实际上会返回一个副本。您正在更改该Top副本的值,而不是实际控制的边距。由于这不会有明显的影响,VB 正确地阻止了它。

You need to assign a whole new margin. In fact, the Marginproperty (or rather, the Paddingclass) is arguably broken since it doesn't allow an easy way to change the individual values.

您需要分配一个全新的边距。事实上,Margin属性(或者更确切地说,Padding类)可以说是损坏的,因为它不允许简单的方法来更改单个值。

Unfortunately, we just have to live with it. So to change just the Topvalue, we need to write:

不幸的是,我们只能忍受它。因此,要仅更改Top值,我们需要编写:

Dim old As Padding = LabelAdapter.Margin
LabelAdapter.Margin = New Padding(old.Left, 8, old.Right, old.Bottom)

Weird, huh?

很奇怪吧?