2010-05-26 45 views
0

我可以使用以下Xmal位的組合框添加到DataGrid:在Silverlight中添加一個組合框到DataGrid

<local:DataGridTemplateColumn Header="SomeHeader" Width="106" HeaderStyle="{StaticResource headerAlignRightStyle}" CellStyle="{StaticResource cellAlignRightStyle}"> 
        <local:DataGridTemplateColumn.CellTemplate> 
         <DataTemplate> 
          <TextBlock Text="{Binding SomeProp}" Margin="4"/> 
         </DataTemplate> 
        </local:DataGridTemplateColumn.CellTemplate> 
        <local:DataGridTemplateColumn.CellEditingTemplate> 
         <DataTemplate> 
          <ComboBox 
           x:Name="SomeCombo" 
           SelectionChanged="SomeCombo_SelectionChanged" 
           ItemsSource="{Binding SomeList}" 
           DisplayMemberPath="Name" 
           /> 
         </DataTemplate> 
        </local:DataGridTemplateColumn.CellEditingTemplate> 
       </local:DataGridTemplateColumn> 

但我想不出是一個明智的方式來獲得,這是COMBOX是行 必然。即當處理組合框SelectionChanged事件時,我無法知道哪些組合框屬於哪個組合框。特別是我不知道該組合框引用的DataGrid數據源 中有什麼對象。

任何幫助將不勝感激。

回答

2

你可以

A),使用雙向綁定,所以你不會有擺在首位擔心的SelectionChanged ComboBox的SelectedItem屬性綁定到您的視圖模型/數據模型的屬性

B)使用DataGridRow.GetRowContainingElement(元素)你的SelectionChanged處理程序,即

private void SomeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
    var comboBox = sender as ComboBox; 
    if (comboBox == null) 
     return; 
    var row = DataGridRow.GetRowContainingElement(comboBox); 
    // Do something with row... 
} 

乾杯,啤酒X

+0

謝謝 - 我現在尋找到正確MVVM ... – bplus 2010-05-26 20:27:12

0

據我所知,當你點擊組合框時,該行應該得到焦點。這也意味着datagrid知道所選項目。

如果您正在尋找所選對象,您應該可以通過datagridName.SelectedItem訪問它。這將返回選定的對象。

請對其進行測試並對解決方案發表評論,因爲我現在無法檢查答案。

1

如果你只是希望得到該行被綁定到項,你可以閱讀的DataContext發件人:

private void SomeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
    var item = sender as FrameworkElement; 
    if (item== null) 
     return; 
    var source = item.DataContext; 
}