使用TemplatedParent的多绑定总是为ActualHeight返回0.0



我试图在ControlTemplate中使用Multibinding来绘制一些线。我的XAML:

                <Line X1="{Binding ActualWidth, RelativeSource={RelativeSource TemplatedParent}}" Y1="0"
                      X2="{Binding ActualWidth, RelativeSource={RelativeSource TemplatedParent}}" Stroke="Red" StrokeThickness="1">
                    <Line.Y2>
                        <MultiBinding Converter="{StaticResource XAMLResourceAddConverter}">
                            <Binding Source="-15"></Binding>
                            <Binding Path="ActualHeight" RelativeSource="{RelativeSource TemplatedParent}"></Binding>
                        </MultiBinding>
                    </Line.Y2>
                </Line>

和我的转换器:

public class AddConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType,
           object parameter, System.Globalization.CultureInfo culture)
    {
        int result =
            Int32.Parse(values[0].ToString()) + Int32.Parse(values[1].ToString());
        return result;
    }
    public object[] ConvertBack(object value, Type[] targetTypes,
           object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException("Cannot convert back");
    }
}

线实际上没有绘制。逐步通过转换器,我发现value[1](应该是ActualHeight)总是通过0.0。我该如何解决这个问题?

在这种情况下可以使用FindAncestor,因为TemplatedParent在绑定

时没有被解析。
<Binding Path="ActualHeight" RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type MyType}}"></Binding>
其次,当您在多绑定中使用硬编码值-15进行第一次绑定时,也许您可以使用转换器参数 内联绑定Y2。

所以如果你可以将转换器XAMLResourceAddConverter更改为IValueConveter,那么也许你可以使用它作为

Y2="{Binding ActualHeight, RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource XAMLResourceAddConverter}, ConverterParameter=-15}"

最新更新