2011-12-13 151 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