私は(あなたがそれを推測した)コントロールから継承するコントロールを持っています。FontSize
またはStyle
プロパティが変更されるたびに通知を受け取りたいです。WPFでは、を呼び出すことでそれを行いDependencyProperty.OverrideMetadata()
ます。もちろん、そのような便利なものはSilverlightにはありません。では、どのようにしてそのような種類の通知を受け取ることができるでしょうか。
5 に答える
ここがより良い方法だと思います。まだ長所と短所を確認する必要があります。
/// 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);
}
そして今、RegisterForNotificationを呼び出して、などの要素のプロパティの変更通知を登録できます。
RegisterForNotification("Text", this.txtMain,(d,e)=>MessageBox.Show("Text changed"));
RegisterForNotification("Value", this.sliderMain, (d, e) => MessageBox.Show("Value changed"));
同じhttp://amazedsaint.blogspot.com/2009/12/silverlight-listening-to-dependency.htmlの私の投稿を参照してください
Silverlight4.0ベータ版を使用しています。
これはかなり嫌なハックですが、双方向バインディングを使用してこれをシミュレートできます。
つまり、次のようなものがあります。
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);
}
}
次に、次のようなバインディングを作成します。
<Canvas>
<Canvas.Resources>
<FontSizeListener x:Key="listener" />
</Canvas.Resources>
<MyControlSubclass FontSize="{Binding Mode=TwoWay, Source={StaticResource listener}, Path=FontSize}" />
</Canvas>
次に、コントロールサブクラスのリスナーのイベントに接続します。
依存関係プロパティの変更通知を外部からリッスンすることはできません。
次のコード行を使用して、依存関係プロパティのメタデータにアクセスできます。
PropertyMetadata metaData = Control.ActualHeightProperty.GetMetadata(typeof(Control));
ただし、公開されるパブリックメンバーは「DefaultValue」のみです。
WPFでこれを行う方法は多数あります。ただし、現在、Silverlight2または3ではサポートされていません。
私が見る唯一の解決策は、LayoutUpdatedイベントをリッスンすることです-はい、私はそれがたくさん呼ばれていることを知っています。ただし、FontSizeまたはStyleが変更されても呼び出されない場合があることに注意してください。
これは私がいつも使用しているものです(ただし、SLではテストしていませんが、WPFでテストしています)。
/// <summary>
/// This method registers a callback on a dependency object to be called
/// when the value of the DP changes.
/// </summary>
/// <param name="owner">The owning object.</param>
/// <param name="property">The DependencyProperty to watch.</param>
/// <param name="handler">The action to call out when the DP changes.</param>
public static void RegisterDepPropCallback(object owner, DependencyProperty property, EventHandler handler)
{
// FIXME: We could implement this as an extension, but let's not get
// too Ruby-like
var dpd = DependencyPropertyDescriptor.FromProperty(property, owner.GetType());
dpd.AddValueChanged(owner, handler);
}