Pour éviter un chevauchement potentiel entre TextBlock et Button, vous pouvez calculer la marge gauche du bouton qui se trouve à côté du TextBlock au centre à l'aide d'un convertisseur de valeur. Cela dit, j'aime toujours la réponse fournie par @Wonko car elle est simple et standard.
Voici le XAML:
<Window x:Class="TextBoxInCenter.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TextBoxInCenter"
Title="MainWindow"
Height="350" Width="525">
<Grid>
<Grid.Resources>
<local:CustomThicknessValueConverter x:Key="CustomThicknessValueConverter" />
</Grid.Resources>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock
x:Name="CenterTextBox"
Grid.Column="0"
Grid.ColumnSpan="2"
Grid.Row="0"
Text="Text in Center"
HorizontalAlignment="Center"
VerticalAlignment="Center"
TextAlignment="Center"/>
<StackPanel
Grid.Column="1"
Grid.Row="0"
Orientation="Horizontal">
<Button
Margin="{Binding ElementName=CenterTextBox,
Path=ActualWidth,
Converter={StaticResource CustomThicknessValueConverter}}"
Height="23"
Content="Click me 1">
</Button>
<Button
Height="23"
Content="Click me 2">
</Button>
</StackPanel>
</Grid>
</Window>
est ici le convertisseur de valeur:
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Data;
namespace TextBoxInCenter
{
public class CustomThicknessValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
Debug.WriteLine("Convert");
Thickness thickness = new Thickness(0, 0, 0, 0);
if (value != null)
{
double actaulwidth = (double)value;
thickness.Left = actaulwidth/2;
}
return thickness;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
Voulez-vous dire que vous voulez que la zone de texte à aligner point mort de votre mise en page, et le bouton pour le droit de la zone de texte (sans affecter le centrage)? –
Oui. J'ai besoin de TextBox aligné au centre mort –