Skip to content

Instantly share code, notes, and snippets.

@euyuil
Last active September 13, 2018 10:37
Show Gist options
  • Save euyuil/8450472 to your computer and use it in GitHub Desktop.
Save euyuil/8450472 to your computer and use it in GitHub Desktop.
WPF: in custom UserControl, create custom DependencyProperty, where you can bind some value to.
public partial class MyUserControl : UserControl
{
// The dependency property definition.
public static readonly DependencyProperty MyStateProperty =
DependencyProperty.Register
(
"MyState", // Name of dependency property.
typeof(string), // Type of dependency property.
typeof(MyUserControl), // Type of the class who owns the dependency property.
new FrameworkPropertyMetadata
(
string.Empty, // Default value of dependency property.
OnMyStatePropertyChanged // Callback function when dependency property is changed.
)
);
// Getter and setter for dependency property.
public string MyState
{
get { return (string)GetValue(MyStateProperty); }
set { SetValue(MyStateProperty, value); }
}
// Callback function to handle the change of dependency property.
public static void OnMyStatePropertyChanged
(
DependencyObject d, // i.e. owner of the dependency property.
DependencyPropertyChangedEventArgs e // Event arguments.
)
{
var control = (MyUserControl)d;
/* Do something for that */
}
/* Other things for MyUserControl */
}
@sachinkamboj
Copy link

It's wrong as to use GetValue and Setvalue we need to inhert the class from DependencyObject class but MyUserControl is already inherited from UserControl.So GetValue is not available.Please resolve this problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment