获取datagrid中的行值

时间:2015-03-03 13:33:23

标签: c# wpf mvvm

我的代码如下

MainWindow.Xaml

      <ListBox Width="400" Margin="10" x:Name="myListBox" 
         ItemsSource="{Binding Path=GridVal}" SelectedItem="{Binding CurrentItem}">
              <ListBox.ItemTemplate>
                   <DataTemplate>
                     <Expander Header="Header1" IsExpanded="True">
                        <StackPanel>
                          <DataGrid
                             x:Name="dataGrid"
                             AutoGenerateColumns="False"
                             ItemsSource="{Binding Path=GridVal}" 
                             Height="250" Width="250" SelectedItem="{Binding CurrentItem}"/>
                    </StackPanel>
                </Expander>
        </DataTemplate>
        </ListBox.ItemTemplate>

MainWindow.Xaml

  public object CurrentItem
  {
    get{return _item;}
    set{_item=value;}
  }

它显示一个包含Expander和Datagrid

的列表框

我想获取datagrid中当前选中的行,此时我无法获取。我正在获取Datatemplate项而不是Datagrid

2 个答案:

答案 0 :(得分:1)

您使用了错误的属性将数据绑定到CurrentItem属性。您应该将数据绑定到DataGrid.SelectedItem property

,而不是SelectedIndex
<DataGrid x:Name="dataGrid" AutoGenerateColumns="False" 
    ItemsSource="{Binding GridVal}" Height="250" Width="250" 
    SelectedItem="{Binding CurrentItem}" />

尽管如@Default所提到的,您也尝试将CurrentItem属性数据绑定到两个不同的控件属性,因此您需要添加一个不同的属性才能使其正常工作。此外,CurrentItem属性应与GridVal集合中的项目类型相同。


更新&gt;&gt;&gt;

您似乎缺少某些信息,因为您还尝试将同一个集合数据绑定到ListBox.ItemsSourceDataGrid.ItemsSource这是不可能的。 DataTemplate内的所有内容都会自动将DataContext设置为上述集合中的项目,例如。

时,每个数据项将在DataContext中设置为DataTemplate

因此,要使当前代码正常工作,该集合中的数据项还应具有CurrentItemGridVal属性,但我猜他们没有。您还应该在Visual Studio的“输出”窗口中出现错误,该错误明确告诉您集合中的任何对象类型都没有CurrentItem属性。

我建议您通读MSDN上的Data Templating Overview‎页面,以帮助您更好地了解情况。

答案 1 :(得分:0)

您可以使用Relative source绑定:

{Binding Path=PathToProperty, RelativeSource={RelativeSource AncestorType={x:Type typeOfAncestor}}}

或使用指定的ElementName:

{Binding Path=DataContext.PathToProperty, ElementName=myListBox}