Last active
September 13, 2018 10:37
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 */ | |
} |
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
你好,请问一下。WPF里允许复用自定义的UserControl吗?
我目前有一个与你上面写的类似的一个Custom UserControl,但是没法继承让子类复用属性。
一旦我继承了之后就会在 xaml自动生成的.g.cs文件中提示找不到 当前继承的子类。