Silverlight:如何接收继承的DependencyProperty中的更改通知

Moj*_*ter 12 silverlight dependency-properties

我有一个控件继承自(你猜对了)控制.我想在更改FontSizeStyle属性时收到通知.在WPF中,我会通过调用来做到这一点DependencyProperty.OverrideMetadata().当然,有用的东西在Silverlight中没有位置.那么,如何收到这类通知呢?

ama*_*int 16

我认为这是一个更好的方法.仍然需要看到利弊.

 /// Listen for change of the dependency property
    public void RegisterForNotification(string propertyName, FrameworkElement element, PropertyChangedCallback callback)
    {

        //Bind to a depedency property
        Binding b = new Binding(propertyName) { Source = element };
        var prop = System.Windows.DependencyProperty.RegisterAttached(
            "ListenAttached"+propertyName,
            typeof(object),
            typeof(UserControl),
            new System.Windows.PropertyMetadata(callback));

        element.SetBinding(prop, b);
    }
Run Code Online (Sandbox Code Playgroud)

现在,您可以调用RegisterForNotification来注册元素属性的更改通知,例如.

RegisterForNotification("Text", this.txtMain,(d,e)=>MessageBox.Show("Text changed"));
RegisterForNotification("Value", this.sliderMain, (d, e) => MessageBox.Show("Value changed"));
Run Code Online (Sandbox Code Playgroud)

http://amazedsaint.blogspot.com/2009/12/silverlight-listening-to-dependency.html上查看我的帖子.

使用Silverlight 4.0 beta.


tos*_*hok 6

这是一个相当恶心的黑客,但你可以使用双向绑定来模拟这个.

即有类似的东西:

public class FontSizeListener {
    public double FontSize {
        get { return fontSize; }
        set { fontSize = value; OnFontSizeChanged (this, EventArgs.Empty); }
    }

    public event EventHandler FontSizeChanged;

    void OnFontSizeChanged (object sender, EventArgs e) {
      if (FontSizeChanged != null) FontSizeChanged (sender, e);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后创建绑定,如:

<Canvas>
  <Canvas.Resources>
     <FontSizeListener x:Key="listener" />
  </Canvas.Resources>

  <MyControlSubclass FontSize="{Binding Mode=TwoWay, Source={StaticResource listener}, Path=FontSize}" />
</Canvas>
Run Code Online (Sandbox Code Playgroud)

然后在你的控制子类中连接到监听器的事件.