To avoid potential overlap between the TextBlock and Button, you can calculate the left margin for the Button that ends up next to the TextBlock in the center using a Value Converter. That said I still like answer provided by @Wonko as it is simple and standard.
Here is the 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>
Here is the Value Converter:
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();
}
}
}