我有一个名为" A"的ViewModel,包含ObservableCollection类型的属性(Of ChannelViewModel)。 Model实际上在这个ChannelViewModel类中,我对此很好。
在View" A"中,我有一个StackSnel,ItemsSource填充了ObservableCollection。我添加了一个DataTemplate来显示一个自定义控件" Channel"而不是ChannelViewModel字符串。 Channel自定义控件需要显示ChannelViewModel数据。
问题是Channel的DataContext没有正确连接到列表的每个项目。我试了很多东西似乎没什么用。我很感激你的帮助!
这是" A"查看代码:
<Window.DataContext>
<ctrls:AViewModel/>
</Window.DataContext>
<StackPanel x:Name="uiStack" Orientation="Horizontal">
<ItemsControl ItemsSource="{Binding Channels}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<ctrls:Channel DataContext="{Binding DataContext}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</StackPanel>
这是&#34; A&#34; ViewModel:
Private aChannels As New ObservableCollection(Of ChannelViewModel)
Property Channels As ObservableCollection(Of ChannelViewModel)
Get
Return aChannels
End Get
Set(value As ObservableCollection(Of ChannelViewModel))
aChannels = value
OnPropertyChanged("Channels")
End Set
End Property
Public Sub New()
AddChannels()
OnPropertyChanged("Channels")
End Sub
Private Sub AddChannels()
For i As Integer = 1 To DeviceConfig.Channels.Count
Channels.Add(New ChannelViewModel(i))
Next
End Sub
Channel UserControl是(简化):
<UserControl.DataContext>
<ctrls:ChannelViewModel />
</UserControl.DataContext>
<StackPanel Orientation="Horizontal">
<Label x:Name="lblChannelNo" Content="{Binding ChannelNo}" />
<Label x:Name="lblChannelName" Content="{Binding ChannelName}" />
</StackPanel>
Channel ViewModel(简化):
Public Class ChannelViewModel
Inherits ViewModelBase
Private aChannelNo As Integer = 0
Property ChannelNo As Integer
Get
Return aChannelNo
End Get
Set(value As Integer)
aChannelNo = value
OnPropertyChanged("ChannelNo")
End Set
End Property
Private aChannelName As String = "N/A"
Property ChannelName As String
Get
Return aChannelName
End Get
Set(value As String)
aChannelName = value
OnPropertyChanged("ChannelName")
End Set
End Property
答案 0 :(得分:1)
好的,问题发生在频道视图中。我认为设置DataContext会覆盖&#34; A&#34;视图。因此删除这些行解决了这个问题:
<UserControl.DataContext>
<ctrls:ChannelViewModel />
</UserControl.DataContext>
我还必须将绑定更改为:
<DataTemplate>
<ctrls:Channel DataContext="{Binding}" />
</DataTemplate>