Reputation:
I'm struggling to get some finer layout issues working on a WPF button, essentially I'm trying to centre the text inside the button? At the moment I dynamically set several buttons in code with something similar to
button1.Content = (option1 != 0.0)
? option1.ToString() + "\n" + "Centre"
: string.Empty;
button2.Content = (option2 != 0.0)
? option2.ToString() + "\n" + "Quite"
: string.Empty;
button3.Content = (option3 != 0.0)
? option.ToString() + "\n" + "Not"
: string.Empty;
and in XAML both vertical and horizontal content alignment is centre?
<Button Height="30" HorizontalAlignment="Left" Margin="254,0,0,0" Name="button1"
VerticalAlignment="Top" Width="50" Click="button_Click"
HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontSize="10"
FontStretch="SemiCondensed"/>
but this doesn't give me the layout I desire, (see below)
How do get both the values on top to be centred and the text on the bottom to be centred?
If I wanted the bottom text to have font size 10 bold and the top to be font size 14 normal - how do I do that?
Many thanks
Upvotes: 0
Views: 2187
Reputation: 375
<StackPanel Visibility="{Binding Path=Option1, Converter={StaticResource myDoubleToVisibilityConverter}}">
<TextBlock HorizontalAlignment="Center" Text="{Binding Path=Option1}"/>
<TextBlock HorizontalAlignment="Center" Text="Center" />
</StackPanel>
you now don`t need set text in code. just realize myDoubleToVisibilityConverter and INotifyPropertyChanged interface
Direct setting of Button`s content, in this case, is some sort of violation on WPF ideology.
Upvotes: 1
Reputation: 1857
I think the easiest way is to use two Textblocks inside the Button and to setup databindings.
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel Orientation="Horizontal" TextBlock.TextAlignment="Center" >
<Button Height="50" Width="80">
<StackPanel>
<TextBlock Text="{Binding Text1}" FontSize="14" />
<TextBlock Text="{Binding Text2}" FontSize="10" FontWeight="Bold"/>
</StackPanel>
</Button>
</StackPanel>
public partial class MainWindow : Window
{
public string Text1 { get; set; }
public string Text2 { get; set; }
public MainWindow()
{
InitializeComponent();
Text1 = "10";
Text2 = "TEST Test";
DataContext = this;
}
}
please also read MVVM / INotifyPropertychanged tutorials if you don't already know this patterns (because my example does not implement this interface, the content of the buttonts will not refresh if you change a TextX property)
Upvotes: 2
Reputation: 29000
Try with this code (\r\n)
button1.Content = (option1 != 0.0)
? option1.ToString() + "\r\n" + "Centre"
: string.Empty;
You can also use Environment.NewLine
Upvotes: 0