wpf 设计器显示只能在 DependencyObject 错误的 DependencyProperty 上设置“绑定”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25286007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 12:20:51  来源:igfitidea点击:

designer shows A 'Binding' can only be set on a DependencyProperty of a DependencyObject error

c#wpf

提问by Nataly87

I've created a user control that has a DependencyProperty, and when I try binding to it I get an error in the designer:

我创建了一个具有 DependencyProperty 的用户控件,当我尝试绑定到它时,在设计器中出现错误:

" 'Binding' cannot be set on the 'ROCValue' property of type 'RocIndicator'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.

" 无法在类型为“RocIndicator”的“ROCValue”属性上设置“绑定”。只能在 DependencyObject 的 DependencyProperty 上设置“绑定”。

Edit:I've added the static modifier, but I still get that error. and yes, I've restarted visual studio.

编辑:我已经添加了静态修饰符,但我仍然收到那个错误。是的,我已经重新启动了 Visual Studio。

public partial class RocIndicator : UserControl
{
    public static readonly DependencyProperty ROCValueProperty =
        DependencyProperty.Register("ROCValue", typeof(double), typeof(RocIndicator),
        new FrameworkPropertyMetadata(0.0, new PropertyChangedCallback(ValueChanged)));


    public double ROCValue
    {
        get { return (double)GetValue(ROCValueProperty); }
        set { SetValue(ROCValueProperty, value); }
    }
}

this is the XAML:

这是 XAML:

<View:RocIndicator ROCValue="{Binding ROC}" Margin="0,10,0,0" HorizontalAlignment="Center" Width="35"/>

but when I build & run it works. why is this error showing?

但是当我构建和运行它时。为什么会显示这个错误?

回答by dkozl

Dependency property declaration must be static:

依赖属性声明必须是static

public static readonly DependencyProperty ROCValueProperty ...

回答by Shakeel Choudhury

I had the same issue once when copying a UserControl from one project to another. I tried closing the solution, restarting Visual Studio and even restarting my PC. None of those worked.

将 UserControl 从一个项目复制到另一个项目时,我曾经遇到过同样的问题。我尝试关闭解决方案,重新启动 Visual Studio,甚至重新启动我的 PC。这些都没有用。

I then unloaded and reloaded the project and this seemed to fix it. (Potentially a Visual Studio build bug).

然后我卸载并重新加载项目,这似乎解决了它。(可能是 Visual Studio 构建错误)。

To unload the project, right click on your project in Solution Explorer and click 'Unload Project'. Then right click again and click 'Reload Project'.

要卸载项目,请在解决方案资源管理器中右键单击您的项目,然后单击“卸载项目”。然后再次右键单击并单击“重新加载项目”。

回答by Alex Parloti

I had the same problem and solved it by deleting the "obj"folder in the project directory and rebuilding the solution.

我遇到了同样的问题,通过删除项目目录中的“obj”文件夹并重建解决方案来解决它。