Я провел тест пользовательских свойств зависимостей для пользовательских элементов управления WPF и не работает ... Пожалуйста, помогите.
Задача:
Используя UserControl - MyCircle, создайте привязываемые свойства CenterX
и CenterY
.
Вот мой код:
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;
}
}
Тест холст:
<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>
Итак, линия на холсте тестирования не следует за центром круга ... Почему?
EDIT:
Примечание:
В коде или конструкторе я никогда не смог изменить свойства CenterX
и CenterY
. Мне нужно, чтобы эти свойства были "связаны" со свойствами левого / верхнего холста ... Это возможно?