WPF依赖属性返回值

Ela*_*lad 1 c# wpf dependency-properties

我是WPF的新手.

假设我定义了一个int依赖属性.DP的目的是返回值+ 1(参见代码).在.Net 2.0中我会写:

private int _myValue = 0;
    public int MyValue
    {
        get { return _myValue + 1; }
        set { _myValue = value; }
    }
Run Code Online (Sandbox Code Playgroud)

您如何声明实现类似行为的DP?


提供的强制仅适用于Set操作.我想修改Get结果.

Ken*_* K. 5

你可以像这样间接地实现它:

public static readonly DependencyProperty ValueProperty =
    DependencyProperty.Register("Value", typeof(int), typeof(OwnerClass),
        new FrameworkPropertyMetadata(0, null, new CoerceValueCallback(CoerceValue)));

public int Value
{
    get { return (int)GetValue(ValueProperty); }
    set { SetValue(ValueProperty, value); }
}

private static object CoerceValue(DependencyObject d, object value)
{
    return (int) value + 1;
}
Run Code Online (Sandbox Code Playgroud)

请查看此链接以获取有关强制的说明.