My question below is answered but I just realised that now the FontSize
only resizes in one direction.
Is there a possibility to bind two paths? Or another option?
Previous question
I have a Grid
[20,20] with TextBox
es in it. In these TextBoxe
s I put numbers. When the application starts up it's fullscreen. If I resize the window the Grid
with the TexBox
es also resizes. But the Font
stays the same. So I want to change the FontSize
when the Window resizes. I tried:
FontSize="{Binding ElementName=aTextBox, Path=Height}"
between the TextBox
tags. But that doesn't work. A binding with the Grid
or Window
with property Height
or Width
didn't work either. With binding to a slider the FontSize
changes according to the the value of the slider. Does anybody have a nice solution?
The Height
property is the initial height of the TextBox
. The ActualHeight
represents the height of the TextBox
as it is drawn on the screen. So your binding becomes:
<TextBox FontSize="{Binding Path=ActualHeight, RelativeSource={RelativeSource Self}, Converter={StaticResource HeightToFontSizeConverter}}" Text="12345" />
Notice that I used a converter because the ratio Height
to FontSize
is not 1:1 and the text is too big for the TextBox
:
class HeightToFontSizeConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
var height = (double) value;
return .65 * height;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
throw new NotImplementedException();
}
}
A simple Viewbox could do the trick, but there are issues.
Refer to this reply.. How to relative scale size of User Control?
I'm in favour of the converter approach as in Julien's reply.
I just did a quick test. If I bind the Text
property of a TextBox
to the Width
of the containing grid the result is NaN
. That would probably be the reason your binding fails.
If I instead bind the FontSize
property of the TextBox
to the ActualWidth
property the binding is OK, and also resizes with the grid. The font is huge though. You would probably need some converter to make the FontSize
smaller.
<Grid x:Name="myGrid">
<TextBox Text="Hello" FontSize="{Binding ElementName=myGrid, Path=ActualWidth}"/>
</Grid>