依赖属性和绑定错误 [英] Dependency Property and Binding Error
问题描述
经过几个小时的搜索,我来找你的帮助:
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 =26FontFamily =Arial/>
< / StackPanel>
PriceView.xaml.cs
public partial class PriceView:UserControl
{
public PriceView()
{
this.InitializeComponent();
this.DataContext = this;
}
#region依赖属性
public static readonly DependencyProperty PriceProperty = DependencyProperty.Register(Price,typeof(float),typeof(PriceView));
public float价格
{
get {return(float)GetValue(PriceProperty); }
set {SetValue(PriceProperty,value); }
}
#endregion
}
我在做什么错了?
这是来自我的依赖关系吗?
感谢@HB的发言我找到了答案: / p>
从不在UserControls上设置DataContext
MainWindow.xaml: / em>
< Exec:PriceView Price ={Binding Test}/>
< TextBlock Text ={Binding Test}/>
PriceView.xaml:
< StackPanel x:name =root>
< TextBlock Text ={Binding Price}FontSize =26FontFamily =Arial/>
< / StackPanel>
PriceView.xaml.cs:
this.root.DataContext = this;
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 ?
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;
这篇关于依赖属性和绑定错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!