[英]How to change the margin of a TextBlock without moving the text?
每當我嘗試調整 TextBlock 的大小時,通常,文本都會隨之移動。 有沒有辦法繞過這種行為,這樣我就可以在不移動文本的情況下調整背景大小?
我已經擺弄了過多的設置,在一些聊天中詢問了周圍的情況,但都沒有結果。
或者,有沒有辦法將文本放置在 TextBlock 的絕對中心? 當我向下調整 TextBlock 的大小時,文本不會移動,但任何其他方向,它都會移動。 我已經處理過文本的水平和垂直對齊等問題,但也遇到了枯燥的問題。
這是一個測試代碼,可以做你想做的事,或者至少給你一些想法。 在屏幕底部,您可以更改上部文本塊的邊距、寬度和高度。
該代碼正在計算文本塊的左/上 position 的移動。 然后設置文本塊的填充以補償該移動。 如果文本超出文本塊的左側或頂部,則填充設置為 0,並且它將跟隨文本塊。 如果文本超出文本塊的右側/底部,您必須注意該怎么做。
計算在 LayoutUpdated 事件處理程序中完成,在面板中完成所有布局安排后調用該事件處理程序。
XAML:
<Grid x:Name="grid" LayoutUpdated="Grid_LayoutUpdated">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock x:Name="textBlock" Text="Test" Height="50" Width="100"/>
<StackPanel Grid.Row="1">
<StackPanel Orientation="Horizontal">
<TextBlock Text="Margin" Width="100" Margin="5"/>
<TextBox Text="{Binding Margin, ElementName=textBlock, Mode=TwoWay}" Margin="5"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Width" Width="100" Margin="5"/>
<TextBox Text="{Binding Width, ElementName=textBlock}" Margin="5"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Height" Width="100" Margin="5"/>
<TextBox Text="{Binding Height, ElementName=textBlock}" Margin="5"/>
</StackPanel>
</StackPanel>
</Grid>
后面的代碼:
public partial class MainWindow : Window
{
public MainWindow()
{
DataContext = this;
InitializeComponent();
Loaded += MainWindow_Loaded;
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
lastTextBlockPos = textBlock.PointToScreen(new Point());
initiateReady = true;
}
bool initiateReady = false;
Point lastTextBlockPos = new Point();
private void Grid_LayoutUpdated(object sender, EventArgs e)
{
if (initiateReady)
{
Point tp = textBlock.PointToScreen(new Point());
if (tp != lastTextBlockPos)
{
//Calculate how much the top left corner of the text block moved during layout.
double left = textBlock.Padding.Left - tp.X + lastTextBlockPos.X;
double top = textBlock.Padding.Top - tp.Y + lastTextBlockPos.Y;
//Set the padding to move the text inside the text block
//If outside the text block, set to left, top most position
//TODO: take care of when the text is outside on the right, bottom side
Thickness tn = new Thickness()
{
Left = left >= 0 ? left : 0,
Top = top >= 0 ? top : 0,
};
textBlock.Padding = tn;
lastTextBlockPos = tp;
//Showing TextBlock bounds for test
Point gp = grid.PointToScreen(new Point());
RectangleGeometry myRectangleGeometry = new RectangleGeometry();
myRectangleGeometry.Rect = new Rect(tp.X - gp.X, tp.Y - gp.Y, textBlock.ActualWidth, textBlock.ActualHeight);
Path myPath = new Path();
myPath.Data = myRectangleGeometry;
myPath.Stroke = Brushes.Goldenrod;
myPath.StrokeThickness = 2;
Grid.SetColumn(myPath, 0);
Grid.SetRow(myPath, 0);
Path old = grid.Children.OfType<Path>().FirstOrDefault();
if (old != null) grid.Children.Remove(old);
grid.Children.Add(myPath);
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.