您是否知道該問題已在Web中進行了多次討論?但我的是一個特例,我仍然沒有找到正確的解決方案。如果DataTemplate嵌套在另一個Datatemplate中,則很難與父模板屬性綁定
場景:Silverlight 4 - 一個TreeView,其數據由兩個HierarchicalDataTemplate顯示,一個顯示第一級數據(即TreeView的父項數據),另一個顯示第二級數據(對於兒童項目)。在子項模板中,我必須將控件的可見性綁定到父模板的數據源類的屬性。
這是XAML代碼:
<UserControl.Resources>
<HierarchicalDataTemplate x:Key="modTreeArtDataParts2">
<Grid>
<TextBlock
Visibility="{Binding ???}"/>
</Grid>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate x:Key="modTreeArtDataParts"
ItemTemplate = "{StaticResource modTreeArtDataParts2}"
ItemsSource = "{Binding RicambiItemList}">
</HierarchicalDataTemplate>
</UserControl.Resources>
<Grid>
<TreeView
ItemTemplate = "{StaticResource modTreeArtDataParts}"
ItemsSource="{Binding RicambiList}"/>
</Grid>
如果是WPF我可以這樣寫:
能見度=「{結合DataContext.Ori,轉換器= {StaticResource的rVisibilityConverter}的RelativeSource = {的RelativeSource AncestorLevel = 2,AncestorType = {x:Type TreeViewItem},Mode = FindAncestor}}「
...它肯定會起作用。但我知道在Silverlight FindAncestor與RealitiveSource的綁定模式不支持。網絡中的解決方案都在的下方,在代碼隱藏的視覺樹中向下滾動。無論是用Behavior還是Attached-Propery來實現它都無關緊要。解決方案是這樣的:
Public Class hideTextBlockBehavior
Inherits Behavior(Of DependencyObject)
Protected Overrides Sub OnAttached()
MyBase.OnAttached()
Dim g As Grid = FindVisualParent(Of Grid)(AssociatedObject)
Dim o As customType = g.DataContext
If o.hide Then AssociatedObject.Visibility = Visibility.Collapsed
End Sub
Private Function FindVisualParent(Of parentItem As DependencyObject)(ByVal obj As DependencyObject) As parentItem
Dim objParent As DependencyObject = obj
While obj Is Nothing = False AndAlso TypeOf obj Is parentItem = False
obj = VisualTreeHelper.GetParent(obj)
End While
Return DirectCast(obj, parentItem)
End Function
End Class
<HierarchicalDataTemplate x:Key="modTreeArtDataParts2">
<Grid>
<TextBlock>
<i:Interaction.Behaviors>
<il:hideTextBlockBehavior/>
</i:Interaction.Behaviors>
</TextBlock>
</Grid>
</HierarchicalDataTemplate>
我用了很多次這樣的解決方案,他們總是工作。但在這種情況下,我的DataTemplate是嵌套到另一個DataTemplate然後,當我在「OnAttached」方法,「AssociatedObject」的屬性「父」是什麼,然後我沒有視覺樹滾動 。
你有什麼建議嗎? 提前謝謝! Pileggi
是的,我認爲,但這有點多餘,不是嗎? – lamarmora 2012-02-03 08:22:33
雖然我認爲Silverlight缺點的大多數解決方法(與WPF的豐富性相反)導致了類似的構造,但它有點多餘。就我個人而言,我發現在自定義代碼中遍歷視覺樹同樣不雅觀。升級到Silverlight 5或使用轉換器將是其他選項。可能的話,如果您也使用視圖模型定位器服務,則可以不使用引用。 – ericontilt 2012-02-03 12:22:00