Resize font in TextBox in Grid

2019-08-10 03:31发布

问题:

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 TextBoxes in it. In these TextBoxes I put numbers. When the application starts up it's fullscreen. If I resize the window the Grid with the TexBoxes 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?

回答1:

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();
  }

}


回答2:

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.



回答3:

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>