2

Control から派生する簡単なカスタム コントロールを作成しました。

このコントロールには、ScaleTransform の xaml でバインドする 2 つの DP があります。

コードビハインド。

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 プロパティを変更した後、問題は発生しません。

そこで、ScaleX と ScaleY のハンドラーを MyControl に追加しました。これらのハンドラーは、手動で 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);

        }
    }
4

1 に答える 1

4

の多くの制限の 1 つにぶつかった可能性がありTemplateBindingます。

したがって、代わりに、相対的なソースと同等のものをテンプレート化された親として使用します。Bindingこれ意味的に同等ですがTemplateBinding、(わずかに) 重いです:

<ScaleTransform ScaleX="{Binding ScaleX,RelativeSource={RelativeSource TemplatedParent}}" ScaleY="{Binding ScaleY,RelativeSource={RelativeSource TemplatedParent}}" />
于 2014-08-31T19:25:12.010 に答える