wpf - how do I apply same margins to all elements

2020-04-22 04:33发布

问题:

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)?

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)

回答1:

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.

  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.

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