1
我创建了一个名为的类,它放在UserControl中,名为时间表。我为创建了一个依赖项属性,时间段为,名为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>
正如你可以看到我已绑定的时期ContainingTimetable属性Timetable1。但是,当我运行该程序时,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')
任何帮助将不胜感激,谢谢。
如果'Timetable'派生自FrameworkElement,则可以简单地使用['Parent'](http://msdn.microsoft.com/zh-cn/library/system.windows.frameworkelement.parent.aspx)属性。此外,属性设置器和因此'Debug.WriteLine'可能永远不会被调用。请参阅[这里](http://msdn.microsoft.com/en-us/library/bb613563.aspx)的解释。 – Clemens
@Clemens谢谢你的建议,但是当我得到它的父类时,Timetable是一个UserControl它返回一个Grid。我明确知道它没有被设置,因为当我引用ContainingTimetable时,我得到一个NullReferenceException。 – Ivel97
对不起,我的意思是当然期。时间表将是期间的父母。 – Clemens