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);
}
}