WPF 依赖属性返回值

发布于 2024-07-27 12:36:14 字数 362 浏览 3 评论 0原文

我对 WPF 还很陌生。

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

private int _myValue = 0;
    public int MyValue
    {
        get { return _myValue + 1; }
        set { _myValue = value; }
    }

How would you suggest a DP that Achieves like behavior?


提供的强制仅适用于 Set 操作。 我想修改获取结果。

I'm fairly new to WPF.

Suppose I defined an int dependency property. The purpose of the DP is to return the value+1 (see code).
In .Net 2.0 I would have written:

private int _myValue = 0;
    public int MyValue
    {
        get { return _myValue + 1; }
        set { _myValue = value; }
    }

How would you declare a DP that achieves similar behavior?


The Coercion that was offered works only for the Set operation. I would like to modify the Get result.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

恰似旧人归 2024-08-03 12:36:14

您可以像这样间接实现它:

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;
}

检查此 链接 有关强制的解释。

You would achieve it indirectly like this:

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;
}

Check this link for an explanation about coercion.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文