Skip to content

Instantly share code, notes, and snippets.

@euyuil
Last active September 13, 2018 10:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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 */
}
@zbin
Copy link

zbin commented Nov 19, 2015

你好,请问一下。WPF里允许复用自定义的UserControl吗?
我目前有一个与你上面写的类似的一个Custom UserControl,但是没法继承让子类复用属性。
一旦我继承了之后就会在 xaml自动生成的.g.cs文件中提示找不到 当前继承的子类。

@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