2010-05-26 50 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; 
}