I did a test on custom dependency properties on WPF userControls, and does not work... Please help.
Task:
Having an UserControl - MyCircle, build the CenterX
and CenterY
bindable properties.
Here is my code:
MyTestCircle.xaml
<Canvas x:Name="mainCanvas" Width="100" Height="100">
<Ellipse x:Name="myCircle" Fill="Red"
Width="{Binding ElementName=mainCanvas, Path=ActualWidth}"
Height="{Binding ElementName=mainCanvas, Path=ActualHeight}"/>
</Canvas>
MyTestCircle.xaml.cs
public partial class MyTestCircle : UserControl
{
public MyTestCircle()
{
InitializeComponent();
}
public double CenterX
{
get { return (double)GetValue(CenterXProperty); }
set { SetValue(CenterXProperty, value); }
}
public static readonly DependencyProperty CenterXProperty =
DependencyProperty.Register("CenterX", typeof(double), typeof(MyTestCircle),
new UIPropertyMetadata(double.NaN,
new PropertyChangedCallback(OnCenterYChanged),
new CoerceValueCallback(OnCenterXCoerceValue)));
public static void OnCenterXChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
MyTestCircle circle = (MyTestCircle)obj;
Canvas.SetLeft(circle, (double)args.NewValue - circle.Width / 2);
}
public static object OnCenterXCoerceValue(DependencyObject source, object obj)
{
MyTestCircle circle = (MyTestCircle)obj;
return Canvas.GetLeft(circle) + circle.Width / 2;
}
public double CenterY
{
get { return (double)GetValue(CenterYProperty); }
set { SetValue(CenterYProperty, value); }
}
public static readonly DependencyProperty CenterYProperty =
DependencyProperty.Register("CenterY", typeof(double), typeof(MyTestCircle),
new UIPropertyMetadata(double.NaN,
new PropertyChangedCallback(OnCenterYChanged),
new CoerceValueCallback(OnCenterYCoerceValue)));
public static void OnCenterYChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
MyTestCircle circle = (MyTestCircle)obj;
Canvas.SetTop(circle, (double)args.NewValue - circle.Height / 2);
}
public static object OnCenterYCoerceValue(DependencyObject source, object obj)
{
MyTestCircle circle = (MyTestCircle)obj;
return Canvas.GetTop(circle) + circle.Height / 2;
}
}
Testing Canvas:
<Canvas x:Name="mainCanvas">
<my:MyTestCircle Canvas.Left="104" Canvas.Top="132" x:Name="myTestCircle1" />
<Line Stroke="Black"
X1="0" Y1="0"
X2="{Binding ElementName=myTestCircle1, Path=CenterX}"
Y2="{Binding ElementName=myTestCircle1, Path=CenterY}"
/>
</Canvas>
So, the Line in the Testing canvas does not follow the center of the circle... Why?
EDIT:
Remark:
In the code or Designer, I could never chanage the CenterX
and CenterY
properties. I need that that properties be "linked" with the Left/Top canvas properties... Is that possible?