依赖属性数据上下文 [英] Dependency Property Datacontext

查看:103
本文介绍了依赖属性数据上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户控件,并且为此设置了一个Datacontext。此用户控件还包含一个依赖项属性。现在,我只想绑定到此属性。



我认为问题与错误的数据上下文有关。

I have a usercontrol, and there is a Datacontext set for it. This usercontrol contains also a Dependency-Property. Now, i want simply bind to this property.

I think the problem has something to do with the wrong datacontext.

usercontrol中的依赖项属性(称为TimePicker)如下:

The dependency-Property in my usercontrol (called TimePicker) looks like this:

public TimeSpan Time
    {
        get { return (TimeSpan)GetValue(TimeProperty); }
        set
        {
            SetValue(TimeProperty, value);
            OnPropertyChanged();
        }
    }

    public static readonly DependencyProperty TimeProperty = DependencyProperty.Register("Time", typeof (TimeSpan), typeof (TimePicker));

我尝试像这样使用它:

<upDownControlDevelopement:TimePicker Grid.Row="1" Time="{Binding Path=TimeValue}" />

当我这样做时,出现以下绑定错误:

When i do this i get the following binding error:

System.Windows.Data Error: 40 : BindingExpression path error: 'TimeValue' property not found on 'object' ''TimePicker' (Name='TimePickerControl')'. BindingExpression:Path=TimeValue; DataItem='TimePicker' (Name='TimePickerControl'); target element is 'TimePicker' (Name='TimePickerControl'); target property is 'Time' (type 'TimeSpan')

任何帮助将不胜感激

问候Michael

PS:您可以在此处

推荐答案

您无需覆盖用户控件的数据上下文。您可以使用RelativeSource将绑定源属性(即TimeValue)指向您喜欢的任何其他源。
例如如果Windows类中具有source属性。您可以简单地将绑定目标指向窗口数据上下文中的源,如下所示:

You don't need to override the data context of user control . You can use RelativeSource to point your binding source property i.e. TimeValue to any other source you like. E.g. If you have the source property in your windows class. You could simply point your binding target to the source in window's data context as follows:

 {Binding Path=DataContext.TimeValue, RelativeSource={ RelativeSource AncestorType={x:Type Window}}}

道歉格式。从iPhone输入

"Apologies for formatting . Typed from iPhone"

这篇关于依赖属性数据上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆