Steven Muhr
Steven Muhr

Reputation: 3379

Dependency Property and Binding Error

After hours of searching, I come for your help :

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

I couldn't found where my binding error was...

In my MainWindow I have :

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

On my TextBlock, the Binding with the Test property is perfectly working.

But for my PriceView control, it's not.

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
}

What am I doing wrong ? Is this coming from my Dependency Properrty ?

Upvotes: 0

Views: 411

Answers (2)

Steven Muhr
Steven Muhr

Reputation: 3379

Thanks to the remark of @H.B I found the answer :

Never set the DataContext on UserControls

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;

Upvotes: 2

brunnerh
brunnerh

Reputation: 185290

What you have is in essence, this:

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

It should be apparent why one binding works while the other does not.

Rule of thumb: Never set the DataContext on UserControls.

Upvotes: 2

Related Questions