WPF: Setting the Width (and Height) as a Percentage Value

前端 未结 7 625
悲&欢浪女
悲&欢浪女 2020-11-27 10:59

Say I want a TextBlock to have its Width equal to it\'s Parent container\'s Width (ie, stretch from side to side) or a percentage of

7条回答
  •  爱一瞬间的悲伤
    2020-11-27 11:28

    I know it's not Xaml but I did the same thing with SizeChanged event of the textbox:

    private void TextBlock_SizeChanged(object sender, SizeChangedEventArgs e)
    {
       TextBlock textBlock = sender as TextBlock;
       FrameworkElement element = textBlock.Parent as FrameworkElement;
       textBlock.Margin = new Thickness(0, 0, (element.ActualWidth / 100) * 20, 0);
    }
    

    The textbox appears to be 80% size of it's parent (well right side margin is 20%) and stretches when needed.

提交回复
热议问题