简体   繁体   English

如何获取DataGridTemplateColumn中的复选框?

[英]How to get checkbox in the DataGridTemplateColumn?

I'm creating a window for user delete multiple registers of database using DataGrid for show data and a Button for execute delete 我正在创建一个窗口供用户删除数据库的多个寄存器,使用DataGrid来显示数据,并使用Button来执行删除

So I putted a DataGridTemplateColumn in the DataGrid and CheckBox in this DataGridTemplateColumn 所以我将DataGridTemplateColumn放在DataGrid并将CheckBox放在此DataGridTemplateColumn

<DataGrid Name="WordList" Margin="10" Width="230" AutoGenerateColumns="False" 
            SelectionMode="Single" SelectionChanged="WordList_SelectionChanged" 
            CanUserAddRows="False">
    <DataGrid.Columns>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <CheckBox Name="WordChecked" HorizontalAlignment="Center" 
                        VerticalAlignment="Center"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTextColumn Binding="{Binding Path=Word}" Header="Word" Width="1*" 
            IsReadOnly="True"/>
    </DataGrid.Columns>
</DataGrid>

Please, how to can I access this CheckBox with C# for check it is checked or not? 请,如何使用C#访问此CheckBox以检查是否已选中?

My recommended approach is to have a List<Item> that is held in the ViewModel and whenever you check the CheckBox in the row the datagrid's SelectedItem will be set and you add the item that was selected to the List . 我推荐的方法是在ViewModel中保存一个List<Item> ,每当您选中该行中的CheckBox ,都会设置datagrid的SelectedItem并将您选择的项目添加到List Then when the button is clicked, you delete all the records that are in the List . 然后,当单击按钮时,将删除“ List中的所有记录。

Ideally you also want to implement this using Command s. 理想情况下,您还想使用Command来实现这一点。

<DataGridTemplateColumn>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <CheckBox IsChecked= "{Binding checked, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" Click="CheckBox_Click"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
private void CheckBox_Click(object sender, RoutedEventArgs e)
{
   int index = DGItems.SelectedIndex;
   DataRowView drv = (DataRowView)DGItems.Items[index];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM