public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
Person pp = new Person();
pp.name = "tt";
}
}
public class Person:DependencyObject
{
public static readonly DependencyProperty nameProperty = DependencyProperty.Register("name", typeof(string), typeof(Person), new PropertyMetadata("熊俊"), new ValidateValueCallback(Islike)); //注册依赖项属性
public string name
{
get { return (string)GetValue(nameProperty); }
set { SetValue(nameProperty, value); }
}
public static bool Islike(object value) //验证回调
{
MessageBox.Show(value.ToString());
return !(value.ToString() == "丑女");
}
}
上面的代码,当初次编译的时候,点击button1,会弹出3次对话框,前两次是弹出"熊俊",这是默认值,第三次弹出"tt",当再次点击的时候,就只弹出"tt"了,只要不退出,以后点击button1,都只弹出"tt"
请问,这是什么原理?
pp.SetValue(Person.nameProperty, "tt");