[英]How to update the property in the angle (custom WPF control)
讓我告訴你我要完成的事情。 這是XAML代碼,代表一個角度三點:
<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; } }
}
但是現在,我想對CUSTOM WPF CONTROL實施最后一個用戶控件:
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
}
}
請檢查最后一個靜態void,我正在嘗試執行以下操作:
// var x = Math.Cos(Angle * (Math.PI / 180))
// var y = Math.Sin(...);
// PART_LINE.X2 = x;
// PART_LINE.Y2 = y;
在事件處理程序中,使用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
}
}
並確保在您的Angle控件的ControlTemplate中,為Line指定適當的名稱:
<Line x:Name="PART_LINE" Stroke="Black" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.