2011-12-13 140 views
0

搜索後幾個小時,我來對你有所幫助:依賴項屬性和綁定錯誤

System.Windows.Data Error: 40 : BindingExpression path error: 'Test' property not found on 'object'

我無法找到我的地方綁定錯誤是......

在我的主窗口,我有:

<Exec:PriceView Price="{Binding Test}"/> 
<TextBlock Text="{Binding Test}"/> 

在我的TextBlock上,Binding with Test屬性完全正常工作。

但是對於我的PriceView控件,它不是。

PriceView.xaml

<StackPanel> 
<TextBlock Text="{Binding Price}" FontSize="26" FontFamily="Arial"/> 
</StackPanel> 

PriceView.xaml.cs

public partial class PriceView : UserControl 
{ 
    public PriceView() 
    { 
     this.InitializeComponent(); 
     this.DataContext = this; 
    } 

    #region Dependency Property 
    public static readonly DependencyProperty PriceProperty = DependencyProperty.Register("Price", typeof(float), typeof(PriceView)); 

    public float Price 
    { 
     get { return (float)GetValue(PriceProperty); } 
     set { SetValue(PriceProperty, value); } 
    } 
    #endregion 
} 

我在做什麼錯? 這是來自我的Dependency Properrty嗎?

回答

1

由於@HB的這句話我找到了答案:

從未設置的DataContext上用戶控件

MainWindow.xaml:

<Exec:PriceView Price="{Binding Test}"/> 
<TextBlock Text="{Binding Test}"/> 

PriceView.xaml:

<StackPanel x:name="root"> 
<TextBlock Text="{Binding Price}" FontSize="26" FontFamily="Arial"/> 
</StackPanel> 

PriceView.xaml.cs:

this.root.DataContext = this; 
+1

更正:使用依賴屬性時,從不設置視圖的DataContext。 – Xcalibur37 2011-12-14 01:11:54

2

你有什麼是在本質上,這一點:

<Exec:PriceView Price="{Binding Test}" 
       DataContext="{Binding RelativeSource={RelativeSource Self}}"/> 
<TextBlock Text="{Binding Test}"/> 

應該清楚爲什麼一個綁定工作,而其他沒有。

經驗法則:千萬不要將DataContext設置爲UserControls

+0

沒有工作。我仍然有同樣的錯誤。我真的不明白爲什麼綁定在TextBlock控件上,而不是在PriceView控件上。 – 2011-12-13 23:56:27