2016-08-25 71 views
0

我有以下XAML:現在如何訪問組合框的SelectedItem裏面的DataTemplate

<ItemsControl x:Name="TextComboPairItemsControl" Grid.Row="1" Grid.ColumnSpan="2" 
        ItemsSource="{Binding Path=AllHeaders.Fields}"> 
     <ItemsControl.ItemTemplate> 
       <DataTemplate> 
        <Grid> 

         <Grid.ColumnDefinitions> 
          <ColumnDefinition /> 
          <ColumnDefinition /> 
         </Grid.ColumnDefinitions> 

         <TextBlock x:Name="TextBlock1" Text="{Binding}" 
            Grid.Column="0" Margin ="2"/> 
         <ComboBox x:Name="ComboBox1" ItemsSource="{Binding ElementName=MainGrid, Path=DataContext.Tags}" 
            SelectedItem="{Binding ElementName=MainGrid, Path=DataContext.TextComboPairList.Combo}" 
            Grid.Column="1" Margin ="2" SelectedIndex="0" IsEditable="True"/> 
        </Grid> 
       </DataTemplate> 
      </ItemsControl.ItemTemplate> 
    </ItemsControl> 

,在我的代碼我希望能夠讀什麼用戶在每個組合框選擇了。爲此,我創建了一個類:

public class TextComboPair 
{ 
    public string TextContent { get; set; } 
    public string ComboContent { get; set; } 
} 

每一對TextBlock和ComboBox都有它自己的上述類的對象。 我還創建了一個列表來存儲所有這些數據對:

public List<TextComboPair> TextComboPairList 
{ 
    get; 
    set; 
} 

它在我的DataContext定義。

因此,例如,如果在屏幕上顯示了三個TextBlock-ComboBox對的列表,並且用戶將在每個ComboBox中選擇他需要的內容,我希望將上述列表填入該數據。

正如您在XAML中看到的,我將選定項綁定到此列表,但我必須做到這一點。

我可以解決這個問題嗎?

回答

0

試試這個:

<ComboBox x:Name="ComboBox1" ItemsSource="{Binding Path=DataContext.Tags, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl }}}" 
           SelectedItem="{Binding RelativeSource={RelativeSource AncestorType={x:Type ItemsControl }}, Path=DataContext.TextComboPairList.Combo}" 
           Grid.Column="1" Margin ="2" SelectedIndex="0" IsEditable="True"/> 
+0

遺憾的是它沒有工作。我的列表仍然爲空。實際上,使用此代碼,我的ComboBox甚至不顯示任何內容。也許是因爲我沒有任何DataGrid。 – Loreno

+0

那麼mainGrid是什麼? –

+0

嗯,它只是網格,而不是DataGrid – Loreno

相關問題