2015-04-20 190 views
0

我有一個名爲「A」,包含ObservableCollection(Of ChannelViewModel)類型的屬性的ViewModel。該模型實際上是在這個ChannelViewModel類中,我對此很滿意。WPF綁定到父項ItemsSource從DataTemplate的DataContext項

在視圖「A」中,我有一個帶有ObservableCollection的ItemsSource的堆棧面板。我添加了一個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> 

這裏是 「A」 視圖模型:

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 

的頻道用戶控件(簡化):

<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 

回答

1

好的,問題出在Channel View中。我認爲設置DataContext覆蓋「A」視圖的上下文。因此,移除這些線解決了這個問題:

<UserControl.DataContext> 
    <ctrls:ChannelViewModel /> 
</UserControl.DataContext> 

我也不得不改變結合:

<DataTemplate> 
    <ctrls:Channel DataContext="{Binding}" /> 
</DataTemplate> 
相關問題