2012-07-11 46 views
0

让我告诉你我正在努力完成什么。这是XAML代码代表一个角度三点:如何更新角度属性(自定义WPF控件)

<Border Width="200" Height="200" BorderBrush="Black" BorderThickness="1"> 
     <Canvas HorizontalAlignment="Center" VerticalAlignment="Center" 
     Width="0" Height="0" 
     RenderTransform="1 0 0 -1 0 0"> 
      <Line X1="0" Y1="0" X2="{Binding CoordinateX}" Y2="{Binding CoordinateY}" Stroke="Black" /> 
      <Line X1="0" Y1="0" X2="100" Y2="0" Stroke="Black" /> 
     </Canvas> 
    </Border> 

我的数据上下文为:

 Test a = new Test(); 

     // degrees * (pi/180) 
     a.Angle = 45 * (Math.PI/180.0); 

     this.DataContext = a; 

public class Test 
{ 
    public Test() { } 
    public double Angle { get; set; } 
    public double CoordinateX { get { return Math.Cos(Angle) * 100; } } 
    public double CoordinateY { get { return Math.Sin(Angle) * 100; } } 
} 

但是现在,我要实现的最后一个用户控制到自定义WPF控件:

public class Angle : Control 
{ 
    static Angle() 
    { 
     DefaultStyleKeyProperty.OverrideMetadata(typeof(Angle), new FrameworkPropertyMetadata(typeof(Angle))); 
    } 

    public double Angle 
    { 
     get { return (double)base.GetValue(AngleProperty); } 
     set { base.SetValue(AngleProperty, value); } 
    } 

    public static readonly DependencyProperty AngleProperty = 
     DependencyProperty.Register("Angle", typeof(double), typeof(Angle), new PropertyMetadata(90.0, new PropertyChangedCallback(AngleChanged))); 

    public double Radius 
    { 
     get { return (double)base.GetValue(RadiusProperty); } 
     set { base.SetValue(RadiusProperty, value); } 
    } 

    public static readonly DependencyProperty RadiusProperty = 
     DependencyProperty.Register("Radius", typeof(double), typeof(Angle), new PropertyMetadata(100)); 

    static void AngleChanged(DependencyObject property, DependencyPropertyChangedEventArgs args) 
    { 
     // here is the part I do not have idea to get "PART_LINE1" and change the values for X2 and Y2 
    } 
} 

请检查上次静态无效,我试图做这样的事情:

 // var x = Math.Cos(Angle * (Math.PI/180)) 
     // var y = Math.Sin(...); 

     // PART_LINE.X2 = x; 
     // PART_LINE.Y2 = y; 

回答

1

在事件处理程序,使用GetTemplateChild方法找到相应的元素,有点像这样:

static void AngleChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) 
{ 
    Angle angleControl = (Angle)obj; 
    Line line = angleControl.GetTemplateChild("PART_LINE") as Line; 
     if (line!= null) 
     { 
      //manipulate the line here 
     } 
} 

,并确保在ControlTemplate中为你的角度控制,你给行适当的名称:

<Line x:Name="PART_LINE" Stroke="Black" /> 
相关问题