当复选框值更改时,wpf会选中行

时间:2017-01-04 10:38:53

标签: c# wpf checkbox

我正在用c#构建一个wpf应用程序。我有一个包含信息的GridView。每行都有一个复选框。单击复选框时,我希望收到行的用户名值(在第1列中)。

现在它正在运行,但必须选择整行。否则我收到一个空例外。

private void CheckBox_breakfast(object sender, RoutedEventArgs e)
{
    Reservation reservation = gridReservations.SelectedItem as Reservation;
    string name = reservation.user_name;
}

如何只选择复选框而不是整行?

已经在网上搜索并尝试了很多,但没有任何作用。

会帮助我很多!

2 个答案:

答案 0 :(得分:2)

您可以尝试将CheckBox本身的DataContext强制转换为预留:

private void CheckBox_breakfast(object sender, RoutedEventArgs e)
{
    CheckBox checkBox = sender as CheckBox;
    Reservation reservation = checkBox.DataContext as Reservation;
    string name = reservation.user_name;
}

如果您没有明确地将CheckBox的DataContext或其中的任何父元素设置为其他内容,那么这应该有用。

答案 1 :(得分:0)

我遇到了与您相同的问题,并且找到了解决方案。

首先,如果您指的是WPF(而不是ASP Web框架),那么您可能指的是Datagrid控件而不是GridView控件。

这进入XAML

<DataGrid>
    <DataGrid.Columns>
       ... <!--other definitions of datagrid columns go here-->
       <DataGridCheckBoxColumn Header="Select to delete">
            <DataGridCheckBoxColumn.ElementStyle>
                <Style> <!-- used the following for design sake to center vertically and horizontally the checkboxes relative to the other content in the datagrid-->
                    <Setter Property="TextBlock.VerticalAlignment" Value="Center" />
                    <Setter Property="TextBlock.HorizontalAlignment" Value="Center" />
                </Style>
            </DataGridCheckBoxColumn.ElementStyle>
        </DataGridCheckBoxColumn>
    </DataGrid.Columns>
</DataGrid>

这应该放在

后面的.xaml.cs代码中
private void getCodMatricol_CheckBox_Selected_in_Datagrid()
    {
        List<int> your_list_of_items_that_correspond_to_checked_checkboxes = new List<int>();
        for (int i = 0; i < datagridGrupeProductie.Items.Count; i++)
        {
            var item = datagridGrupeProductie.Items[i];
            var mycheckbox = datagridGrupeProductie.Columns[10].GetCellContent(item) as CheckBox;
            var myTextBlock = datagridGrupeProductie.Columns[0].GetCellContent(item) as TextBlock;
            if ((bool)mycheckbox.IsChecked)
            {
               your_list_of_items_that_correspond_to_checked_checkboxes.Add(int.Parse(myTextBlock.Text));
            }
        }
    }

在我的示例中,我提取了数据网格中第一列的内容,其中包含一些由整数表示的代码。

注意:数据网格中行和列的索引从[0]开始(实际上是C#中的大多数索引)

如果datadgrid中的列定义为(经常使用)

</DataGridTextColumn> </DataGridTextColumn>

然后它承载一个TextBlock元素。

var myTextBlock = datagridGrupeProductie.Columns[0].GetCellContent(item) as TextBlock;

您必须处理此控件的Text属性以读取其内容并根据需要进行转换。

int.Parse(myTextBlock.Text

接下来,您将要提取的内容填写在List集合中:

your_list_of_items_that_correspond_to_checked_checkboxes.Add(int.Parse(myTextBlock.Text));

此外,如果您想对该值进行任何操作,则必须遍历集合

foreach (var item in your_list_of_items_that_correspond_to_checked_checkboxes)
            {
                //do whatever needed on each item
            }
相关问题