C# WPF:试图为TextBlock添加边框却作用于整个Grid的问题
解决TextBlock边框意外应用到整个Grid的问题
嘿,这问题我之前也踩过坑!你写的XAML里,Border确实是包裹着TextBlock的,但为啥看起来整个Grid都有边框?其实是WPF默认布局行为搞的鬼——Border默认会拉伸填满父容器(也就是你的Grid)的可用空间,因为它的HorizontalAlignment和VerticalAlignment默认值是Stretch,哪怕里面只放了个TextBlock,Border还是会占满整个Grid区域,让你误以为边框是给Grid加的。
给你两个简单的修复方案:
方案一:让Border自适应TextBlock尺寸(推荐)
把原本TextBlock上的对齐和边距属性移到Border上,这样Border会紧紧包裹住TextBlock,不会乱拉伸:
<Border BorderBrush="Black" BorderThickness="6" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="65,54,0,0"> <TextBlock x:Name="txtInputUsername" TextWrapping="Wrap" Text="Username" TextAlignment="Center" FontFamily="Open Sans" FontSize="20" Background="#FFF3F3F3" OpacityMask="Black"/> </Border>
原理很简单:给Border设置Left和Top的对齐方式后,它就不会再拉伸填满Grid,而是根据内部TextBlock的大小来调整自身尺寸,边框自然就只围着TextBlock了。
方案二:手动指定Border的尺寸
如果你想精确控制Border的大小,直接给它加Width和Height属性就行(数值根据你的TextBlock实际显示大小调整):
<Border BorderBrush="Black" BorderThickness="6" Width="130" Height="45" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="65,54,0,0"> <TextBlock x:Name="txtInputUsername" TextWrapping="Wrap" Text="Username" TextAlignment="Center" FontFamily="Open Sans" FontSize="20" Background="#FFF3F3F3" OpacityMask="Black"/> </Border>
试一下上面的代码,应该就能看到边框乖乖出现在TextBlock周围啦!
内容的提问来源于stack exchange,提问作者Isonlaxman
相关产品推荐
相关产品推荐

