WPF之依赖项属性
using System ;
using System. Collections. Generic ;
using System. Linq ;
using System. Text ;
using System. Threading. Tasks ;
namespace Learn
{
public class MyTest
{
private string name = "" ;
public string Name { get ; set ; } = "" ;
}
}
public string UserName
{
get => ( string ) GetValue ( UserNameProperty) ;
set { SetValue ( UserNameProperty, value ) ; }
}
public readonly static DependencyProperty UserNameProperty;
static MyControl ( )
{
FrameworkPropertyMetadata metadata = new FrameworkPropertyMetadata ( "123456" )
{
AffectsArrange = true ,
AffectsMeasure = true ,
AffectsParentArrange = true ,
AffectsParentMeasure = true ,
} ;
UserNameProperty = DependencyProperty. Register ( "UserName" , typeof ( string ) , typeof ( MyControl ) , metadata) ;
}
using System ;
using System. Collections. Generic ;
using System. Linq ;
using System. Text ;
using System. Threading. Tasks ;
using System. Windows ;
namespace LearnCanvas
{
public class MyControl : FrameworkElement
{
public string UserName
{
get => ( string ) GetValue ( UserNameProperty) ;
set { SetValue ( UserNameProperty, value ) ; }
}
public readonly static DependencyProperty UserNameProperty;
static MyControl ( )
{
FrameworkPropertyMetadata metadata = new FrameworkPropertyMetadata ( "123456" )
{
AffectsArrange = true ,
AffectsMeasure = true ,
AffectsParentArrange = true ,
AffectsParentMeasure = true ,
CoerceValueCallback = MyCoerceValue,
PropertyChangedCallback = MyPropertyChanged
} ;
UserNameProperty = DependencyProperty. Register ( "UserName" , typeof ( string ) , typeof ( MyControl ) , metadata, new ValidateValueCallback ( MyValidate) ) ;
}
private static bool MyValidate ( object obj)
{
return true ;
}
private static object MyCoerceValue ( DependencyObject d, object baseValue)
{
return baseValue;
}
private static void MyPropertyChanged ( DependencyObject d, DependencyPropertyChangedEventArgs e)
{
}
}
}