【问题标题】:Dependency Property and Binding Error依赖属性和绑定错误
【发布时间】:2012-01-19 20:03:17
【问题描述】:

经过几个小时的搜索,我来寻求您的帮助:

System.Windows.Data 错误:40:BindingExpression 路径错误:“测试” 在“对象”上找不到属性

我找不到我的绑定错误在哪里...

在我的主窗口中,我有:

<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
}

我做错了什么? 这是来自我的依赖属性吗?

【问题讨论】:

    标签: c# wpf silverlight xaml data-binding


    【解决方案1】:

    你所拥有的本质上是这样的:

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

    应该很清楚为什么一种绑定有效而另一种无效。

    经验法则:永远不要在UserControls 上设置DataContext。

    【讨论】:

    • 没有用。我仍然有同样的错误。我真的不明白为什么绑定适用于 TextBlock 控件而不是 PriceView 控件。
    【解决方案2】:

    感谢@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;
    

    【讨论】:

    • 更正:使用依赖属性时不要设置视图的DataContext。
    • 为什么不呢?我已经成功地同时使用了两者。您只需要了解,当您设置 DataContext 时,您在同一级别上的其他绑定使用相同的上下文,除非您使用 RelativeSource 或 ElementName 指定不同的源。
    猜你喜欢
    • 1970-01-01
    • 2014-04-10
    • 1970-01-01
    • 2016-01-22
    • 2012-11-08
    • 2012-08-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-31
    相关资源
    最近更新 更多