user9641573
user9641573

Reputation:

Bind width of element to a percentage of another element's width

Is there any way to link an UI element's width to another element's width percentage? if my Datagrid is 100px, I want my TextBlock to be 60% of that = 60px (the datagrid's width is dynamic).

Upvotes: 0

Views: 1786

Answers (3)

Andy
Andy

Reputation: 12276

The way I'd probably do this is with a converter.
You can bind the width of the TextBlock to the ActualWidth of the DataGrid and then use a converter to apply the factor.

public class MultiplyConverter : MarkupExtension, IValueConverter
{
    public double Multiplier { get; set; }

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

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return null;
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return this;
    }
}

Something like:

Width="{Binding ActualWidth,  ElementName=MyDataGrid, Converter={ui:MultiplyConverter Multiplier=.6}}"

Upvotes: 1

Aousaf Rashid
Aousaf Rashid

Reputation: 5738

I don't think it is very hard, or is it ?

myTextBox.Height = ((double)DataGrid.Height / 60) * 100

Upvotes: 0

Ismail Hakki Tekin
Ismail Hakki Tekin

Reputation: 71

In Grid you can give proportional width for columns, like:

<ColumnDefinition Width="5*"/>
<ColumnDefinition Width="3*"/>

First one could be you DataGrid and second one is the TextBlock. This way TextBlock will have 60% of the DataGrid's width, and also will be responsive to size changes.

Upvotes: 0

Related Questions