12 April 2011

WPF - Dependency property for databinding

To databind on a property of a user control this property needs to be a dependency property. The following is how I implemented that:

public partial class HelpUserControl : UserControl {
  public static readonly DependencyProperty HelpTextProperty =
    DependencyProperty.Register("HelpText",
                                typeof(string),
                                typeof(HelpUserControl),
                                new PropertyMetadata(OnHelpTextChanged));
  public string HelpText {
    get { return (string)this.GetValue(HelpTextProperty); }
    set { this.SetValue(HelpTextProperty, value); }
  }

  private static void OnHelpTextChanged(
                      DependencyObject target,
                      DependencyPropertyChangedEventArgs e) {
    (target as HelpUserControl).imgIcon.ToolTip = e.NewValue.ToString();
  }
}

No comments:

Post a Comment