我有一个ItemsControl绑定到一个对象列表。 我为ItemsControl设置了一个ItemTemplate ...并且在ItemTemplate中我有一个ListView,我想绑定到另一个Objects列表。
如何在ItemsControl.ItemTemplate中获取对ListView的访问权限,以便将其DataContext设置为第二个对象列表?
以下是我的例子:
<ItemsControl x:Name="DealerShips" ItemsSource="{Binding}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Expander Header="{Binding Name}" Foreground="White">
<ListView x:Name="CarTypes" ItemsSource="{Binding}">
<ListView.ItemTemplate>
<CheckBox Content="{Binding Path=Name}" IsChecked="{Binding Path=InStock}"></CheckBox>
</ListView.ItemTemplate>
</ListView>
</Expander>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
在我的VB.NET代码中,我可以参考我的“DealerShips”ItemsControl来将DataContext设置为List(Of DealerShip)对象。我无法弄清楚如何访问“CarTypes”ListView,以便我可以设置它的DataContext。
Public Class CarsWindow
Private _listOfDealerShips As ObservableCollection(Of DealerShip)
Private _listOfInventory As ObservableCollection(Of Car)
Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
_listOfDealerShips = New ObservableCollection(Of DealerShip)
listOfDealerShips.Add(New DealerShip("A"))
listOfDealerShips.Add(New DealerShip("B"))
listOfDealerShips.Add(New DealerShip("C"))
_listOfInventory = New ObservableCollection(Of Cars)
listOfDealerShips.Add(New Car("TypeX",True))
listOfDealerShips.Add(New Car("TypeY",False))
listOfDealerShips.Add(New Car("TypeZ",True))
DealerShips.DataContext = _listOfDealerShips
' I cannot access CarTypes....
'CarTypes.DataContext = listOfInventory
End Sub
Private Class DealerShip
Public Property Name As String
Public Sub New
End Sub
Public Sub New(ByVal name As String)
Me.Name = name
End Sub
End Class
Private Class Car
Public Property Name As String
Public Property InStock As Boolean
Public Sub New
End Sub
Public Sub New(ByVal name As String, ByVal isInStock As Boolean)
Me.Name = name
Me.InStock = isInStock
End Sub
End Class
End Class
感谢您的帮助!
-Frinny
答案 0 :(得分:0)
您是否可以设置包含列表并将其公开的viewmodel,将cars窗口的DataContext设置为viewmodel的实例(可能通过DI),然后将xaml中的listview更改为如下所示:
<ListView x:Name="CarTypes" ItemsSource="{Binding DataContext.ListOfInventory, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}">
答案 1 :(得分:0)
我最终创建了一个包含两个列表的类。 像这样:
Public Class DealershipDetails
Public Property ListOfDealerShips As ObservableCollection(Of DealerShip)
Public Property ListOfInventory As ObservableCollection(Of Car)
Public Sub New()
ListOfDealerShips = New ObservableCollection(Of DealerShip)
ListOfDealerShips.Add(New DealerShip("A"))
ListOfDealerShips.Add(New DealerShip("B"))
ListOfDealerShips.Add(New DealerShip("C"))
ListOfInventory = New ObservableCollection(Of Cars)
ListOfInventory.Add(New Car("TypeX",True))
ListOfInventory.Add(New Car("TypeY",False))
ListOfInventory.Add(New Car("TypeZ",True))
End Sub
End Class
这样我可以将ItemsControl绑定到DealershipDetails类的实例,并有选择地将ItemsControl中的控件绑定到适当的列表。
虽然这种方法有效,但我原来的问题仍然没有答案。 我不知道如何访问子控件。
-Frinny