经过几个小时的搜索,我来寻求你的帮助:
System.Windows.Data错误:40:BindingExpression路径错误:'测试' 在'对象'上找不到的属性
我找不到我的绑定错误...
在我的MainWindow中,我有:
<Exec:PriceView Price="{Binding Test}"/>
<TextBlock Text="{Binding Test}"/>
在我的TextBlock上,使用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
}
我做错了什么? 这来自我的依赖性问题吗?
答案 0 :(得分:2)
你所拥有的本质上是:
<Exec:PriceView Price="{Binding Test}"
DataContext="{Binding RelativeSource={RelativeSource Self}}"/>
<TextBlock Text="{Binding Test}"/>
很明显为什么一个绑定有效而另一个没有绑定。
经验法则:永远不要在DataContext
上设置UserControls
。
答案 1 :(得分:1)
感谢@ H.B的评论,我找到了答案:
永远不要在UserControls上设置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;