簡體   English   中英

依賴屬性和綁定錯誤

[英]Dependency Property and Binding Error

經過數小時的搜索,我來為您提供幫助:

System.Windows.Data錯誤:40:BindingExpression路徑錯誤:在“對象”上找不到“測試”屬性

我找不到綁定錯誤所在的位置...

在我的MainWindow中,我有:

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

在我的TextBlock上,具有Test屬性的Binding可以正常工作。

但是對於我的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
}

我究竟做錯了什么 ? 這是否來自我的依賴財產?

本質上講,您擁有的是:

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

顯而易見的是,為什么一個綁定有效而另一個綁定無效。

經驗法則:切勿在UserControls上設置DataContext

感謝@HB的評論,我找到了答案:

永遠不要在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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM