Auto-sizing elements based on layout position

2019-02-21 05:01发布

Basically I want to lay out visual elements that can change their content according to location where they would be laid. I want to do it in WPF but you might be able to suggest general algorithm without knowing much about WPF.

Example: Consider WrapPanel that contains only Labels that hold some text. When a Label is laid by WrapPanel at the beginning of new row then all the leading white spaces will be removed from its text. That will indeed make the Label shorter.

The only think that knows about where exactly will be such Label laid is WrappPanel that does layouting. So one approach to do this is to code custom Panel that overrides MeasureOverride and ArrangeOverride and change Labels inside MeasureOverride before calling Measure on the Label. I don't like this because:

  1. It is ugly hack (Panel and especially MeasureOverride and ArrangeOveride should only position children not change them).
  2. I'm not sure but I think that if I changed a Label inside MeasureOverride the Label would cause layout to be updated in response which would lead to another (recursive) call to MeasureOverride (=> infinite loop).

So please suggest the right design for this scenario. How should it do this? One that comes to my mind is to:

  1. Have regular WrapPanel.
  2. Every times its Width or Height is changed or some children is changed (its children might be repositioned) update children before MeasureOverride and ArrangeOverride is called.
  3. During the process of updating children (2.) no call to Measure or Arrange of the WrapPanel can be made. Question: How do I temporally inhibit all such calls ?

Before you suggest that I use RichTextBox or TextBlock deal with white space at the beginning of the lines note that Labels and white spaces are just an example - it is little more complicated. But If I know how to solve 'Labels and white spaces' correctly I'll know how to solve real problem too.

If you want to know why do I need do this have a look on my question Create guitar chords editor in WPF and H.B.'s answer.

0条回答
登录 后发表回答