无法绑定到我的依赖项属性

时间:2013-11-21 20:11:08

标签: wpf binding

我在一个继承自Canvas的类中有一个依赖属性,如下所示:

public partial class HueVisualizer : Canvas
{
    public HueVisualizer()
    {
        InitializeComponent();
    }

    public decimal InnerHue
    {
        get { return (decimal)GetValue(HueProperty); }
        set { SetValue(HueProperty, value); }
    }

    // Using a DependencyProperty as the backing store for InnerHue,Saturation and Luminance.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty HueProperty =
        DependencyProperty.Register("InnerHue", typeof(decimal), typeof(LuminanceVisualizer), new FrameworkPropertyMetadata((decimal)0, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
}

我正试图在Xaml中绑定它,就像这样:

<UserControl x:Class="Project1.UserControl1"
         x:Name="TheControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:project1="clr-namespace:Project1"
         mc:Ignorable="d"
         d:DesignHeight="120" d:DesignWidth="300">
...
    <Grid Grid.Row="0" x:Name="HueGrid">
        <project1:HueVisualizer x:Name="HueVisual" 
                                InnerHue ="{Binding ElementName=TheControl, Path=Hue, Mode=TwoWay}"
                                Height="20"
                                Width="{Binding ElementName=TheControl, Path=Width}"/>
    </Grid>
<UserControl />

为了完整性,我试图绑定的属性:

    public partial class UserControl1 : UserControl, INotifyPropertyChanged
{


    public decimal Hue
    {
        get { return (decimal)GetValue(HueProperty); }
        set { SetValue(HueProperty, value); }
    }

    ...

    // Using a DependencyProperty as the backing store for Hue.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty HueProperty =
        DependencyProperty.Register("Hue", typeof(decimal), typeof(UserControl1), new 
        FrameworkPropertyMetadata((decimal)0));
...
}

但是,当我尝试运行/调试项目时,InitializeComponent()的{​​{1}}会出现例外情况:

UserControl1

无论我看多少次示例,我觉得InnerHue应该是一个有效的依赖属性。我还仔细检查以确保Canvas是一个DependencyObject(如果不是,GetValue和SetValue应该抛出编译器错误)。我做错了什么?由于我是WPF的新手,我不禁觉得我错过了一些明显的东西。

1 个答案:

答案 0 :(得分:2)

您为DependencyProperty提供了错误的所有者类型

你写过LuminanceVisualizer,它应该是HueVisualizer。

   public static readonly DependencyProperty HueProperty =
    DependencyProperty.Register("InnerHue", typeof(decimal), 
                      typeof(LuminanceVisualizer), // Replace with HueVisualizer 
                     new FrameworkPropertyMetadata((decimal)0, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault))