c# – 在xaml中绑定Rect Width和Height

我试图在ViewPort中绑定Rect的宽度和高度,如下所示:

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

我的绑定在其他地方工作正常但在这里我收到以下错误消息:

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

编辑我理解错误消息.我的问题是如何解决它.如何绑定rect的高度和宽度?

最佳答案 像这样使用MultiBinding:

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

使用这样的多值转换器:

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();
    }
}
点赞