wpf - 如何将相同的边距应用于面板中的所有元素?

时间:2022-06-09 14:27:10

Is there a way of automatically tells all children items (e.g. labels, textboxes etc) to have a margin of 5, within a panel (e.g. dockpanel)?

有没有办法在面板(例如dockpanel)中自动告知所有子项(例如标签,文本框等)的边距为5?

i.e. as opposed to having to set the margin for each element separately - also noting setting the margin on the panel itself is no good as then the panel has the margin not the elements.

也就是说,不必分别为每个元素设置边距 - 同时注意设置面板本身的边距并不好,因为面板的边距不是元素。

by the way - I note there doesn't seem to be a PADDING element on the DockPanel (which would have helped)

顺便说一句 - 我注意到DockPanel上似乎没有PADDING元素(这会有所帮助)

1 个解决方案

#1


5  

I believe the answer is "no". Margin is not inheritable the way, say, font size is, so you would need to do one of the following:

我相信答案是“不”。保证金不是可继承的,比如字体大小,所以你需要做以下其中一种:

  1. Use a Grid instead of a DockPanel. This would allow you to use row and column definitions to maintain consistent spacing between items.

    使用Grid而不是DockPanel。这将允许您使用行和列定义来维护项之间的一致间距。

  2. Use a style. You will still have to reference the style for each element (e.g., Style="{StaticResource MarginStyle}", which will require more typing than just Margin="10,5", but it would allow you to keep the margin values all in one place.

    使用一种风格。你仍然需要引用每个元素的样式(例如,Style =“{StaticResource MarginStyle}”,这将需要更多的输入,而不仅仅是Margin =“10,5”,但它可以让你保留所有的边距值一个地方。

  3. Bite the bullet and set the margin of each element individually.

    咬紧牙关并单独设置每个元素的边距。

#1


5  

I believe the answer is "no". Margin is not inheritable the way, say, font size is, so you would need to do one of the following:

我相信答案是“不”。保证金不是可继承的,比如字体大小,所以你需要做以下其中一种:

  1. Use a Grid instead of a DockPanel. This would allow you to use row and column definitions to maintain consistent spacing between items.

    使用Grid而不是DockPanel。这将允许您使用行和列定义来维护项之间的一致间距。

  2. Use a style. You will still have to reference the style for each element (e.g., Style="{StaticResource MarginStyle}", which will require more typing than just Margin="10,5", but it would allow you to keep the margin values all in one place.

    使用一种风格。你仍然需要引用每个元素的样式(例如,Style =“{StaticResource MarginStyle}”,这将需要更多的输入,而不仅仅是Margin =“10,5”,但它可以让你保留所有的边距值一个地方。

  3. Bite the bullet and set the margin of each element individually.

    咬紧牙关并单独设置每个元素的边距。