first_page the funky knowledge base
personal notes from way, _way_ back and maybe today

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

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>

[http://stackoverflow.com/questions/717299/wpf-setting-the-width-and-height-as-a-percentage-value]

mod date: 2010-03-22T20:35:14.000Z