使用TemplatedParent的多重绑定始终为ActualHeight返回0.0

时间:2014-07-15 00:43:30

标签: wpf wpf-controls

我尝试在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");
    }
}

Line实际上并没有绘制。通过转换器,我发现value[1](应该是ActualHeight)总是以0.0的形式出现。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

在这种情况下您可以使用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}"