如何在WPF Gridview中获取选中的行值

时间:2018-04-27 13:53:05

标签: c# wpf datagridview

我在WPF中创建了两列的gridview。一个用于DataGridTextColumn,另一个用于DataGridCheckBoxColumn。

<DataGrid AutoGenerateColumns="False" Name="dataGrid1">

 <DataGrid.Columns>
                <DataGridTextColumn Header="MyString" Binding="{Binding MyString}" />
                <DataGridCheckBoxColumn Header="MyBool" Binding="{Binding MyBool}" />
            </DataGrid.Columns>
        </DataGrid>

现在,我想获取已检查项目的文本值

var SelectedList = new List<checkedBoxIte>();
            StringBuilder aa = new StringBuilder();
            for (int i = 0; i < dataGrid1.Items.Count; i++)
            {
                var item = dataGrid1.Items[i];
                var mycheckbox = dataGrid1.Columns[1].GetCellContent(item) as CheckBox;
                var myTextBox = dataGrid1.Columns[0].GetCellContent(item) as TextBox;
                if ((bool)mycheckbox.IsChecked)
                {
                    SelectedList.Add(item[i]);
                    //aa.Append(myTextBox.Text);
                }
            }

我怎么能这样做。

1 个答案:

答案 0 :(得分:0)

您不应该使用TextBox,而应该使用TextBlock,因为DataGridView WPF实际包含的内容是var SelectedList = new List<checkedBoxIte>(); StringBuilder aa = new StringBuilder(); for (int i = 0; i < dataGrid1.Items.Count; i++) { var item = dataGrid1.Items[i]; var mycheckbox = dataGrid1.Columns[1].GetCellContent(item) as CheckBox; var myTextBlock = dataGrid1.Columns[0].GetCellContent(item) as TextBlock; if ((bool)mycheckbox.IsChecked) { SelectedList.Add(item[i]); aa.Append(myTextBlock.Text); } }

所以改变你的代码:

$items = Item::with(['subitems' => function($query) {
    $query->where('language_id', '=', 1);
}])->get();