简体   繁体   中英

how to bind fontsize for wpf textbox?

I have a textbox control that works appropriately, without binding, while its font size should be changed dynamically.

I wanted to do it right and work using binding.

I tried to bind the FontSize using (xaml):

<UserControl x:Class="<ClassName>"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" Focusable="True"
         d:DesignHeight="300" d:DesignWidth="300">
<Grid>
    <TextBox x:Name="_textBox" Visibility="Visible" xml:space="preserve"
             Background="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type UserControl}},Path=Background}"
             Foreground="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type UserControl}},Path=Foreground}"
             FontFamily="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type UserControl}},Path=FontFamily}"
             BorderBrush="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type UserControl}},Path=BorderBrush}"
             Text="{Binding MultilineText}"
             FontSize="{Binding Path=MultilineFontSize}"
             KeyUp="_textBox_KeyUp"
             PreviewTextInput="_textBox_PreviewTextInput"
             DataObject.Pasting="_textBox_Pasting"
             VerticalContentAlignment="Top"
             PreviewKeyDown="TextBox_OnPreviewKeyDown"
             TextWrapping="Wrap"
             ScrollViewer.VerticalScrollBarVisibility="Visible"
             />
</Grid>

and in the code behind:

private double _multilineFontSize;
public double MultilineFontSize
    {
        get { return GetBestFittingFontSize();  }
        set
        {
            if (value != _multilineFontSize)
            {
                _multilineFontSize = value;
                OnPropertyChanged("MultilineFontSize");
            }
        }
    }

The only use for _multilineFontSize is to replace _textbox.Text wherever I used it (in events etc).

GetBestFittingFontSize() is a function (that works appropriately) and calculates the font size I need to use. Take it as given. It returns double.

It doesn't work. Does any one have any idea why? (maybe some DataContext issues?)

You can try to use the ViewBox which can be used to scale its content.

<Viewbox StretchDirection="Both" Stretch="Uniform">
    <local:UserControl1 Height="100" Width="100"/>
</Viewbox>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM