Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind Rect Width and Height in xaml

I am trying to bind the width and height of a Rect in a ViewPort like this:

<VisualBrush.Viewport>
    <Rect Width="{Binding Path=MyWidth}" Height="{Binding Path=MyHeight}"/>
</VisualBrush.Viewport>

My binding works fine elsewhere but here I get the following error message:

A 'Binding' cannot be set on the 'Width' property of type 'Rect'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.

Edit I understand the error message. My question is how to work around it. How do I bind the height and width of the rect?

like image 390
Daltons Avatar asked Jan 27 '16 09:01

Daltons


1 Answers

Use a MultiBinding like this:

<VisualBrush.Viewport>
    <MultiBinding>
        <MultiBinding.Converter>
            <local:RectConverter/>
        </MultiBinding.Converter>
        <Binding Path="MyWidth"/>
        <Binding Path="MyHeight"/>
    </MultiBinding>
</VisualBrush.Viewport>

with a multi-value converter like this:

public class RectConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        return new Rect(0d, 0d, (double)values[0], (double)values[1]);
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}
like image 102
Clemens Avatar answered Oct 23 '22 22:10

Clemens