2010-06-24 102 views
1

我是WPF的新手,所以這可能比看起來更容易。我有一個DataTable對象,我將其設置爲組合框的itemssource。對於DataTable中的每一行我想要一個ComboBoxItem。對於每個ComboBoxItem,我希望爲該列的當前行中的相應值創建每個列名稱和文本框的標籤。沒有我嘗試似乎工作,但繼承人在XAML的datatemplate我的鏡頭。在WPF中如何綁定父控件的itemssource中的集合

<Grid x:Name="LayoutRoot" Background="White" Height="107" Width="358"> 
    <ComboBox Name="pCombo" ItemsSource="myTable"> 
     <ComboBox.ItemTemplate> 
      <DataTemplate> 
       <StackPanel DataContext="{Binding pCombo.ItemsSource.Columns}"> 
        <TextBlock Text="{Binding ColumnName}"></TextBlock> 
       </StackPanel> 
       <StackPanel DataContext="{Binding pCombo.ItemsSource.Rows}"> 
        <TextBox Text="{Binding RowValue}"></TextBlock> 
       </StackPanel> 
      </DataTemplate> 
     </ComboBox.ItemTemplate> 
    </ComboBox> 
</Grid> 

我知道我所有的綁定是錯誤的我只是不知道應該在那裏而不是。感謝任何幫助我的人。

回答

0

XAML:

<ListView ItemsSource="{Binding Path=Tbl}"> 
     <ListView.ItemTemplate> 
      <DataTemplate> 
       <ComboBox ItemsSource="{Binding}"> 
        <ComboBox.ItemTemplate> 
         <DataTemplate> 
          <StackPanel Orientation="Horizontal"> 
           <Label Content="{Binding Path=Key}"></Label> 
           <Label Content="{Binding Path=Value}"></Label> 
          </StackPanel> 
         </DataTemplate> 
        </ComboBox.ItemTemplate> 
       </ComboBox> 
      </DataTemplate> 
     </ListView.ItemTemplate> 
    </ListView> 

後面的代碼:

private object tbl = new[] 
    { 
    new[] { 
       new KeyValuePair<string, string>("col1", "val1"), new KeyValuePair<string, string>("col2", "val1") 
      }, 
    new[] { 
       new KeyValuePair<string, string>("col1", "val2"), new KeyValuePair<string, string>("col2", "val2") 
      }, 
    new[] { 
       new KeyValuePair<string, string>("col1", "val3"), new KeyValuePair<string, string>("col2", "val3") 
      } 
    }; 

    public object Tbl { get { return tbl; } set { tbl = value; } } 

不要忘記設置的DataContext(即窗口的.ctor)是這樣的:

DataContext = this; 

我只希望你能明白這一點!

+0

所以我不能在集合中使用集合?我必須創建一個新的對象來創建我想要使用的值的列表? – 2010-06-24 17:22:29

+0

我的意思是說,表格中的數據看起來像一個對象(行列表,每行有一列列/列值對)。在我的示例中,我沒有使用表格進行綁定。 我想你可以用上面相同的方式綁定到一個沒有問題的表。 試着按照每個控件如何綁定到實際數據。 我會試着用桌子來舉個例子,但我沒有時間。 Regards ... – Padel 2010-06-24 18:03:37

+0

我試過了,問題在於列名。我想不出一個簡單的解決方案。我能做的最多的是將每行的值綁定到組合框(不包含列名),併爲每一行都設置一個組合框。 爲了將列表視圖綁定到表格屬性({Binding Path = Table})的路徑,將組合框綁定到ItemsArray({Binding Path = ItemsArray})並將標籤綁定到當前對象({Binding} )。 希望它有助於...... – Padel 2010-06-24 19:38:48

相關問題