Wpf 未设置依赖项属性

Wpf 未设置依赖项属性,wpf,vb.net,data-binding,dependency-properties,Wpf,Vb.net,Data Binding,Dependency Properties,我创建了一个名为Period的类,它被放置在名为timeline的用户控件中。我已经为Period创建了一个名为ContainingTimetable的依赖属性,以便Period可以访问其包含时间表的属性 以下是依赖项属性: Public Shared ReadOnly ContainingTimetableProperty As DependencyProperty = DependencyProperty.Register( "ContainingTimetable", GetTyp

我创建了一个名为Period的类,它被放置在名为timeline的用户控件中。我已经为Period创建了一个名为ContainingTimetable的依赖属性,以便Period可以访问其包含时间表的属性

以下是依赖项属性:

Public Shared ReadOnly ContainingTimetableProperty As DependencyProperty = DependencyProperty.Register(
    "ContainingTimetable", GetType(Timetable), GetType(Period), new PropertyMetadata(Nothing))

Public Property ContainingTimetable As Timetable
    Get
        Return DirectCast(GetValue(ContainingTimetableProperty), Timetable)
    End Get
    Set
        SetValue(ContainingTimetableProperty, Value)
        Debug.WriteLine("Timetable has been set")
    End Set
End Property
以下是XAML中的控件:

<local:Timetable Margin="50,25,21,68" UseLayoutRounding="True" PixelToMinuteRatio="2" StartTime="9:00" x:Name="Timetable1">

     <local:Period Background="#72000000" VerticalAlignment="Top" Day="Sunday" StartTime="9:00"
                      EndTime="10:20" Margin="0,0,1,0" ContainingTimetable="{Binding ElementName=Timetable1}"/>

</local:Timetable>

非常感谢您的帮助。

您可以使用Period.Parent获取容器。但是,由于timeline是一个UserControl,因此它只返回immidete容器,而不是UserControl的实例。因此,如果用户控件由两个网格组成,一个在另一个周期内。父控件将返回一个网格而不是时间表

为了解决这个问题,你可以检查家长是否是时间表,如果不是,再上一层再检查。循环直到它是正确的类型

代码如下:

    Dim TimetableObject As DependencyObject
    TimetableObject = Me.Parent

    Do While (Not TimetableObject.GetType() = GetType(WPFTimetableCreator.Timetable))
        TimetableObject = VisualTreeHelper.GetParent(TimetableObject)
    Loop

在我的例子中,我将属性更改为只读,并通过此方法在内部设置它。

如果
timeline
派生自FrameworkElement,您可以简单地使用该属性。此外,可能永远也不会调用属性设置程序和
Debug.WriteLine
。请参阅以获得解释。@Clemens感谢您的建议,但由于时间表是一个用户控件,所以当我得到它的父控件时,它会返回一个网格。我肯定知道它没有被设置,因为当我引用ContainingTimetable时,我得到一个NullReferenceException。“时间表将是这段时间的母体。”克莱门斯,这就是我认为你的意思。当我得到Period.Parent时,它返回一个网格,因为这是它所在的用户控件的一部分。@Clemens感谢你的回答,我找到了一个解决方法,并发布了一个答案。非常感谢。
    Dim TimetableObject As DependencyObject
    TimetableObject = Me.Parent

    Do While (Not TimetableObject.GetType() = GetType(WPFTimetableCreator.Timetable))
        TimetableObject = VisualTreeHelper.GetParent(TimetableObject)
    Loop