从Datagrid单元格或行中获取文本

问题描述:

您好,我正在使用数据网格在WPF中显示可观察的集合. 现在如何从DataGrid中获取选定的行文本,以便调用函数. 这是我的XAML:

Hello i am using the data grid to show an observable collection in WPF. Now how can i get the selected row text from the DataGrid so i can call a function. Here is my XAML:

<DataGrid x:Name="dataGrid" HorizontalAlignment="Left" Margin="0,77,0,0" VerticalAlignment="Top" Height="720" Width="664" ItemsSource="{Binding Items}" AutoGenerateColumns="False" Grid.ColumnSpan="2" SelectedCellsChanged="dataGrid_SelectedCellsChanged">
        <DataGrid.Columns>
            <DataGridTextColumn Header="ProjectName" MinWidth="100" Binding="{Binding Path=ProjectName,Mode=TwoWay}" IsReadOnly="True"></DataGridTextColumn>
            <DataGridTextColumn Header="Name" MinWidth="100" Binding="{Binding Path=Name,Mode=TwoWay}" IsReadOnly="True"></DataGridTextColumn>
            <DataGridTextColumn Header="Path" MinWidth="460" Binding="{Binding Path=Path,Mode=TwoWay}" IsReadOnly="True"></DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>

如何从选定的单元格或行中获取文本?

How can i get the text from the selected cell or row?

如果绑定到的Items集合是IEnumerable<T>,则可以将DataGridSelectedItem属性强制转换为T:

If the Items collection you bind to is an IEnumerable<T>, you could cast the SelectedItem property of the DataGrid to T:

YourItemType obj = dataGrid.SelectedItem as YourItemType;
string name = obj.Name;

或者您可以将SelectedItem属性绑定到T类型的属性,就像您绑定ItemsSource属性一样:

Or you could bind the SelectedItem property to a property of type T, just as you bind the ItemsSource property:

<DataGrid x:Name="dataGrid" ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}" ...>