WPF: Aligning the base line of a Label and its TextBox

前端 未结 5 1820
梦如初夏
梦如初夏 2021-02-03 20:26

Let\'s say I have a simple TextBox next to a Label:


    
        
5条回答
  •  滥情空心
    2021-02-03 20:45

    This question is not as trivial as it looks and the accepted answers lacks details. If you try custom heights with the controls, you will see issues.

    First, this is the correct implementation as answered by User7116.

    
      
      MyText
     
    

    The tricky part is that there two level of vertical alignments here so understand how the alignments works.

    When we specify alignment for a control, we are telling it how to position itself in the parent container (See documentation). So when we specify VerticalAlignment="Center"> to the TextBox we are telling it that this TextBox should appear vertically centered in parent stackpanel.

    Now the actual text inside that TextBox could also use vertical alignment within that TextBox! This is the 2nd level and actually quite tricky and is answered here.

    If you experiment with setting the Label's height above to say 50 as well, you will see they will not align again. This is because Label is now taking larger area and its text inside that area is not vertical aligned so it doesn't look aligned again.

    The code for above is:

        
            
             MyText
        
    

    Luckily when control height is default (like label control), it's just tall enough to contain the text so the inside alignment doesn't matter. But it comes into play if someone is setting custom heights for these controls and its better to understand how this works.

提交回复
热议问题