依赖属性使用场景
1. 希望可在样式中设置属性。
2. 希望属性支持数据绑定。
3. 希望可使用动态资源引用设置属性。
4. 希望从元素树中的父元素自动继承属性值。
5. 希望属性可进行动画处理。
6. 希望属性系统在属性系统、环境或用户执行的操作或者读取并使用样式更改了属性以前的值时报告。
7. 希望使用已建立的、WPF 进程也使用的元数据约定,例如报告更改属性值时是否要求布局系统重新编写元素的可视化对象。
依赖属性生成
PropertyMetadata 后面可以有默认值,
一个PropertyChangedCallback 当值改变的时候的触发方法
一个 CoerceValueCallback 对值进行限定 强制改变
-
-
public
int MyProperty
-
{
-
get {
return (
int)GetValue(MyPropertyProperty); }
-
set { SetValue(MyPropertyProperty,
value); }
-
}
-
-
// Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc...
-
public
static
readonly DependencyProperty MyPropertyProperty =
-
DependencyProperty.Register(
"MyProperty",
typeof(
int),
typeof(ownerclass),
new PropertyMetadata(
0,oncall));
-
-
private static void oncall(DependencyObject d, DependencyPropertyChangedEventArgs e)
-
{
-
// 当值改变时 可以触发
-
}
还有FrameworkPropertyMetadata 多了数据验证ValidateValueCallback
-
public
static
readonly DependencyProperty SimpleDPProperty =
-
DependencyProperty.Register(
"SimpleDP",
typeof(
double),
typeof(SimpleDPClass),
-
new FrameworkPropertyMetadata((
double)
0.0,
-
FrameworkPropertyMetadataOptions.None,
-
new PropertyChangedCallback(OnValueChanged),
-
new CoerceValueCallback(CoerceValue)),
-
new ValidateValueCallback(IsValidValue));
-
-
private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
-
{
-
Console.WriteLine(
"当值改变时,我们可以做的一些操作,具体可以在这里定义: {0}", e.NewValue);
-
}
-
-
private static object CoerceValue(DependencyObject d, object value)
-
{
-
Console.WriteLine(
"对值进行限定,强制值: {0}",
value);
-
return
value;
-
}
-
-
private static bool IsValidValue(object value)
-
{
-
Console.WriteLine(
"验证值是否通过,返回bool值,如果返回True表示验证通过,否则会以异常的形式暴露: {0}",
value);
-
return
true;
-
}