首页 文章

与ScaleTransform绑定的模板在自定义控件中不起作用

提问于
浏览
2

我创建了从Control派生的简单自定义控件 .

这个控件有2个DP,我在ScaleTransform上的xaml中绑定 .

Code behind.

public class MyControl : Control
{
        public static readonly DependencyProperty ScaleXProperty = DependencyProperty.Register(
        "ScaleX", typeof (double), typeof (MyControl), new FrameworkPropertyMetadata(OnScaleXChanged));

    public static readonly DependencyProperty ScaleYProperty = DependencyProperty.Register(
        "ScaleY", typeof (double), typeof (MyControl), new FrameworkPropertyMetadata(OnScaleYChanged));

                public double ScaleX
    {
        get { return (double) GetValue(ScaleXProperty); }
        set { SetValue(ScaleXProperty, value); }
    }

    public double ScaleY
    {
        get { return (double) GetValue(ScaleYProperty); }
        set { SetValue(ScaleYProperty, value); }
    }
}

XAML.

<Style TargetType="{x:Type local:MyControl}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:MyControl}">
                <Border Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">

                    <Border.LayoutTransform>
                        <ScaleTransform ScaleX="{TemplateBinding ScaleX}" ScaleY="{TemplateBinding ScaleY}" />
                    </Border.LayoutTransform>


                    <Image HorizontalAlignment="Stretch"
                           VerticalAlignment="Stretch"
                           Source="{TemplateBinding Icon}"
                           StretchDirection="Both" />
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

我在Window中使用MyControl . 我在LayoutTransform后面的Window代码中更改了ScaleX和ScaleY属性后就没有了 .

所以我为MySptrol添加了处理程序,用于ScaleX和ScaleY . 我这些处理程序我manualy做ScaleTransform . 这有效 . 那么TemplateBinding中的问题在哪里?

使用此解决方法ScaleTransform工作 .

private static void OnScaleXChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is MyControl)
        {
            var ctrl = d as MyControl;

            var x = (double) e.NewValue;

            ctrl.LayoutTransform = new ScaleTransform(x, ctrl.ScaleY);

        }
    }

1 回答

  • 3

    您可能已经遇到了 TemplateBinding 的许多限制之一 .

    因此,使用等效的 Bindingrelative source 作为 templated parent ,它在语义上等同于 TemplateBinding 但是(略微)更重:

    <ScaleTransform ScaleX="{Binding ScaleX,RelativeSource={RelativeSource TemplatedParent}}" ScaleY="{Binding ScaleY,RelativeSource={RelativeSource TemplatedParent}}" />
    

相关问题