代码之家  ›  专栏  ›  技术社区  ›  Ivel97

未设置依赖项属性

  •  1
  • Ivel97  · 技术社区  · 11 年前

    我创建了一个名为 时期 它被放置在名为 时间表 。我已为创建了依赖项属性 时期 打电话 控制时间表 以便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的ContainingTimetable属性绑定到 时间表1 。然而,当我运行程序时,ContainingTimetable属性从未设置在周期上。我还收到了以下错误:

    System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=Timetable1'. BindingExpression:(no path); DataItem=null; target element is 'Period' (Name=''); target property is 'ContainingTimetable' (type 'Timetable')
    

    如有任何帮助,将不胜感激,谢谢。

    1 回复  |  直到 11 年前
        1
  •  0
  •   Ivel97    11 年前

    您可以使用Period.Prent获取容器。然而,由于Timetable是一个UserControl,这将只返回immdete容器,而不是UserControl的实例。因此,如果UserControl由两个网格组成,一个在另一个Period.Prent中,则返回一个网格而不是时间表。

    为了解决这个问题,你可以检查家长是否有时间表,如果没有,可以再上一级,然后再次检查。循环通过,直到其类型正确。

    代码如下:

        Dim TimetableObject As DependencyObject
        TimetableObject = Me.Parent
    
        Do While (Not TimetableObject.GetType() = GetType(WPFTimetableCreator.Timetable))
            TimetableObject = VisualTreeHelper.GetParent(TimetableObject)
        Loop
    

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

    推荐文章