从Datagrid单元格或行中获取文本 [英] Get Text from Datagrid cell or Row

查看:157
本文介绍了从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}" ...>

这篇关于从Datagrid单元格或行中获取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆