c# - 私有(private) WPF 依赖属性

标签 c# wpf dependency-properties

在我的 WPF 项目中,我需要为多个具有相同值的属性设置动画。所以我的想法是创建一个自定义的、私有(private)的依赖属性来应用动画。不幸的是这似乎不起作用。 DependencyPropertyDescriptor.FromProperty() 始终为此属性返回 null。这是代码:

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(CurrentInaccuracyRadiusProperty)); 
    });
  }

  private void UpdateInaccuracyCircle(double curRadius) {
    // do something here
  }
}

还有其他方法来创建私有(private)依赖属性吗?

最佳答案

我不明白你为什么要这样做,我在声明中附加回调时没有遇到任何问题,例如像这样的东西:

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方法应该是静态的)

如果您想坚持使用实例方法:

private static readonly DependencyProperty CurrentInaccuracyRadiusProperty =
    DependencyProperty.Register
    (
        "CurrentInaccuracyRadius",
        typeof(double),
        typeof(PedestrianVisual),
        new UIPropertyMetadata(0.0, (s, e) =>
        {
            ((PedestrianVisual)s).UpdateInaccuracyCircle((double)e.NewValue);
        })
    );

关于c# - 私有(private) WPF 依赖属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6340827/

相关文章:

wpf - 为所有控件设置 VerticalAlignment 属性

wpf - 使用 XAML 停止事件冒泡

c# - .Net 3.5 的 WPF 日期选择器控件

wpf - 错误: “' Subjects' property was already registered by 'Period' ” is raised when more than one control is placed on the form

c# - 从类访问 Properties.Settings.Default?

C# 到 Python 转换器

c# - 创建 ObservableCollection<T> 类

使用 MySql 的 C# Windows 应用程序

silverlight - 如何在 "dependency property changed"上设置断点?

c# - 进度条的 Visibility 属性在运行时不会改变