WPF: Setting the Width (and Height) as a Percentage Value WPF: Setting the Width (and Height) as a Percentage Value wpf wpf

WPF: Setting the Width (and Height) as a Percentage Value


You can put the textboxes inside a grid to do percentage values on the rows or columns of the grid and let the textboxes auto-fill to their parent cells (as they will by default). Example:

<Grid>    <Grid.ColumnDefinitions>        <ColumnDefinition Width="2*" />        <ColumnDefinition Width="3*" />    </Grid.ColumnDefinitions>    <TextBox Grid.Column="0" />    <TextBox Grid.Column="1" /></Grid>

This will make #1 2/5 of the width, and #2 3/5.


The way to stretch it to the same size as the parent container is to use the attribute:

 <Textbox HorizontalAlignment="Stretch" ...

That will make the Textbox element stretch horizontally and fill all the parent space horizontally (actually it depends on the parent panel you're using but should work for most cases).

Percentages can only be used with grid cell values so another option is to create a grid and put your textbox in one of the cells with the appropriate percentage.


Typically, you'd use a built-in layout control appropriate for your scenario (e.g. use a grid as a parent if you want scaling relative to the parent). If you want to do it with an arbitrary parent element, you can create a ValueConverter do it, but it probably won't be quite as clean as you'd like. However, if you absolutely need it, you could do something like this:

public class PercentageConverter : IValueConverter{    public object Convert(object value,         Type targetType,         object parameter,         System.Globalization.CultureInfo culture)    {        return System.Convert.ToDouble(value) *                System.Convert.ToDouble(parameter);    }    public object ConvertBack(object value,         Type targetType,         object parameter,         System.Globalization.CultureInfo culture)    {        throw new NotImplementedException();    }}

Which can be used like this, to get a child textbox 10% of the width of its parent canvas:

<Window x:Class="WpfApplication1.Window1"    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    xmlns:local="clr-namespace:WpfApplication1"    Title="Window1" Height="300" Width="300">    <Window.Resources>        <local:PercentageConverter x:Key="PercentageConverter"/>    </Window.Resources>    <Canvas x:Name="canvas">        <TextBlock Text="Hello"                   Background="Red"                    Width="{Binding                        Converter={StaticResource PercentageConverter},                        ElementName=canvas,                        Path=ActualWidth,                        ConverterParameter=0.1}"/>    </Canvas></Window>