WPF Binding Width to Parent. Width * 0.3

I want to bind the control width to the parent width, but to a specific scale. Is there a way to do something like this:

<Rectangle  Name="rectangle1" Width="{Binding ActualWidth*0.3, ElementName=thumbnailCanvas, UpdateSourceTrigger=PropertyChanged}" Height="{Binding ActualHeight, ElementName=thumbnailCanvas, UpdateSourceTrigger=PropertyChanged}"/>
+4
source share
2 answers

Of course, but you will need to use a converter. Something like that:

using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Markup;

namespace WpfTestBench.Converters
{
    public class PercentageConverter : MarkupExtension, IValueConverter
    {
        private static PercentageConverter _instance;

        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return System.Convert.ToDouble(value) * System.Convert.ToDouble(parameter);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return _instance ?? (_instance = new PercentageConverter());
        }
    }
}

And your XAML will look like this:

<Window x:Class="WpfTestBench.ScaleSample"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:converters="clr-namespace:WpfTestBench.Converters"
        Title="Scale sample" Height="300" Width="300">
    <Grid Name="ParentGrid">
        <Rectangle
            Width="{Binding Path=ActualWidth, ElementName=ParentGrid, Converter={converters:PercentageConverter}, ConverterParameter='0,5'}"
            Stroke="Black" StrokeThickness="2" />
    </Grid>
</Window>
+13
source

I would recommend just doing this in XAML using the grid columns and width type *:

<Window x:Class="NameSpace.WindowName"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="300" Width="300">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="2*" />
        </Grid.ColumnDefinitions>

        <Grid Grid.Column="0"></Grid><!--This item take up 1/3 of window width-->
        <Grid Grid.Column="1"></Grid> <!--This item take up remaining 2/3 of window width-->

    </Grid>
</Window>

You can change the ratio of the number of columns by changing the numbers to * in the width of the column. Here it is set as 1 and 2, so the grid will be divided into 3 (the sum of all * widths), from 1/3 of the width to the first column and from 2/3 to the second column.

+5

All Articles