代码之家  ›  专栏  ›  技术社区  ›  red-X

使用委托、静态和依赖属性时出现问题

  •  1
  • red-X  · 技术社区  · 16 年前

    我正在尝试设置一个名为radius的私有变量的动画,它可以工作。然而,当它发生变化时,我试图执行一个函数,这将是一个相当大的问题。

    我的代码在下面,它不会运行,因为它有以下错误 非静态字段、方法或属性“apppart.setChildrenPosition()”需要对象引用

    明确地 新的setChildrenPositionDelegate(setChildrenPosition) 这句话的这一部分 part.dispatcher.beginInvoke(新的setChildrenPositionDelegate(setChildrenPosition),新对象());

    感谢任何能帮助我的人。

    class AppPart : Shape
    {
        public string name
        { get; set; }
    
        public List<AppPart> parts
        { get; set; }
    
        private double radius
        {
            get { return (double)GetValue(radiusProperty); }
            set { SetValue(radiusProperty, value); }
        }
        public static readonly DependencyProperty radiusProperty = DependencyProperty.Register(
                "radius",
                typeof(double),
                typeof(AppPart),
                new PropertyMetadata(
                new PropertyChangedCallback(radiusChangedCallback)));
    
    
    
        private delegate void SetChildrenPositionDelegate();
    
        private void SetChildrenPosition()
        {
            //do something with radius
        }
    
        private static void radiusChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            AppPart part = d as AppPart;
            part.Dispatcher.BeginInvoke(new SetChildrenPositionDelegate(SetChildrenPosition), new Object());
        }
    
        private void AnimateRadius(double start, double end)
        {
            DoubleAnimation ani = new DoubleAnimation();
            ani.From = start;
            ani.To = end;
            ani.FillBehavior = FillBehavior.HoldEnd;
            ani.Duration = new Duration(new TimeSpan(0, 0, 0, 3, 0));
            ani.Completed += delegate
            {
                Console.WriteLine("ani ended");
            };
            this.BeginAnimation(AppPart.radiusProperty, ani);
        }
    }
    
    2 回复  |  直到 16 年前
        1
  •  1
  •   Jon Skeet    16 年前

    当然-你只需要给代表一个目标。我个人会这样分开:

    AppPart part = d as AppPart;
    // This creates a delegate instance associated with "part" - so it will
    // effectively call part.SetChildrenPosition() accordingly
    SetChildrenPositionDelegate action = part.SetChildrenPosition;
    part.Dispatcher.BeginInvoke(action, new Object());
    

    (你需要 new Object() 顺便说一句,部分?)

        2
  •  1
  •   Justice    16 年前

    尝试: part.Dispatcher.BeginInvoke(() => part.SetChildrenPosition()));