Private WPF dependency property
In my WPF project I need to animate several properties with the same value. So my idea was to create a custom, private dependency property to which the animation will be applied. Unfortunately this doesn't seem to work. DependencyPropertyDescriptor.FromProperty()
always returns null
for this property. Here is the code:
public partial class PedestrianVisual : UserControl {
private static readonly DependencyProperty CurrentInaccuracyRadiusProperty =
DependencyProperty.Register("CurrentInaccuracyRadius", typeof(double), typeof(PedestrianVisual));
private double CurrentInaccuracyRadius {
get { return (double)GetValue(CurrentInaccuracyRadiusProperty); }
set { SetValue(CurrentInaccuracyRadiusProperty, value); }
}
public PedestrianVisual() {
InitializeComponent();
// This returns "null" all the time.
DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromProperty(
CurrentInaccuracyRadiusProperty, typeof(PedestrianVisual));
dpd.AddValueChanged(this, (s, e) => {
UpdateInaccuracyCircle((double)GetValue(Cu开发者_如何学运维rrentInaccuracyRadiusProperty));
});
}
private void UpdateInaccuracyCircle(double curRadius) {
// do something here
}
}
Is there any other way to create a private dependency property?
I don't understand why you would do it that way, i did not encounter any problems when attaching the callback in the declaration, e.g. something like this:
private static readonly DependencyProperty CurrentInaccuracyRadiusProperty =
DependencyProperty.Register
(
"CurrentInaccuracyRadius",
typeof(double),
typeof(PedestrianVisual),
new UIPropertyMetadata(0.0, (s, e) =>
{
UpdateInaccuracyCircle((PedestrianVisual)s, (double)e.NewValue);
})
);
(UpdateInaccuracyCircle
method should be static in this case)
If you want to stick with the instance method:
private static readonly DependencyProperty CurrentInaccuracyRadiusProperty =
DependencyProperty.Register
(
"CurrentInaccuracyRadius",
typeof(double),
typeof(PedestrianVisual),
new UIPropertyMetadata(0.0, (s, e) =>
{
((PedestrianVisual)s).UpdateInaccuracyCircle((double)e.NewValue);
})
);
To further update H.B's answer, the standard approach is along these lines:
static readonly DependencyProperty CurrentInaccuracyRadiusProperty =
DependencyProperty.Register
(
"CurrentInaccuracyRadius",
typeof(double),
typeof(PedestrianVisual),
new UIPropertyMetadata(0.0, OnCurrentInaccuracyRadiusChanged)
);
static void OnCurrentInaccuracyRadiusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var pedVisual = d as PedestrianVisual;
if (pedVisual != null)
pedVisual.OnCurrentInaccuracyRadiusChanged((double)e.OldValue, (double)e.NewValue);
}
void OnCurrentInaccuracyRadiusChanged(double oldValue, double newValue)
{
UpdateInaccuracyCircle(newValue);
}
精彩评论