2013-11-21 54 views
0

我在從畫布繼承,像這樣一類的依賴屬性:不能綁定到我的依賴屬性

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

然而,當我嘗試運行/調試項目,我收到一封電子郵件xception上InitializeComponent()UserControl1的:

A 'Binding' cannot be set on the 'InnerHue' property of type 'HueVisualizer'. A 
'Binding' can only be set on a DependencyProperty of a DependencyObject. 

無論多少次,我看的例子,它在我看來,InnerHue應該是一個有效的依賴項屬性。我也加倍檢查,以確保Canvas是一個DependencyObject(如果它不是,GetValue和SetValue應該拋出一個編譯器錯誤)。我在世界上做了什麼不正確的事情?由於我對WPF比較陌生,所以我不禁覺得我錯過了一些明顯的東西。

回答

1

你給了錯誤的所有者類型爲您的DependencyProperty

你寫LuminanceVisualizer,它應該是HueVisualizer。

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

儘管四組人眼看着代碼,我們沒有發現錯字。感謝您的快速回復! – Taedrin

+0

這是一個非常常見的錯誤,我用一個代碼段來阻止這個.. 也可以在你的初始值中寫入0.0 –

+0

你確定嗎?我認爲編譯器將0.0作爲double/float處理,這與decimal不兼容。 – Taedrin