2014-08-31 61 views
2

我创建了简单的自定义控件,该控件从Control派生。模板绑定到ScaleTransform不能在自定义控件中工作

这个控件有2个DP,我在ScaleTransform中绑定xaml。

后面的代码。

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。在Window代码后面更改ScaleX和ScaleY属性之后,LayoutTransform不会触发。

所以我为MyX for 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); 

     } 
    } 

回答

2

你可能打的TemplateBinding许多限制之一。

因此,而不是使用相当于Binding相对源模板父这是语义上等同于TemplateBinding但(略)重:

<ScaleTransform ScaleX="{Binding ScaleX,RelativeSource={RelativeSource TemplatedParent}}" ScaleY="{Binding ScaleY,RelativeSource={RelativeSource TemplatedParent}}" /> 
相关问题