Dependency Property and Binding Error
经过数小时的搜索,我来为您提供帮助:
System.Windows.Data Error: 40 : BindingExpression path error: 'Test'
property not found on 'object'
我找不到我的绑定错误在哪里...
在我的MainWindow中,我有:
1 2 | <Exec:PriceView Price="{Binding Test}"/> <TextBlock Text="{Binding Test}"/> |
在我的TextBlock上,具有Test属性的绑定可以正常工作。
但是对于我的PriceView控件,不是。
PriceView.xaml
1 2 3 | <StackPanel> <TextBlock Text="{Binding Price}" FontSize="26" FontFamily="Arial"/> </StackPanel> |
PriceView.xaml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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 } |
我在做什么错?
这是我的依赖属性产生的吗?
感谢@ H.B的评论,我找到了答案:
请不要在UserControls上设置DataContext
MainWindow.xaml:
1 2 | <Exec:PriceView Price="{Binding Test}"/> <TextBlock Text="{Binding Test}"/> |
PriceView.xaml:
1 2 3 | <StackPanel x:name="root"> <TextBlock Text="{Binding Price}" FontSize="26" FontFamily="Arial"/> </StackPanel> |
PriceView.xaml.cs:
1 | this.root.DataContext = this; |
本质上是这样的:
1 2 3 | <Exec:PriceView Price="{Binding Test}" DataContext="{Binding RelativeSource={RelativeSource Self}}"/> <TextBlock Text="{Binding Test}"/> |
很明显,为什么一个绑定起作用而另一个绑定不起作用。
经验法则:切勿在