WPF Datagridrow根据选定的comobox项目更改背景颜色和复选框值

时间:2018-04-25 09:42:16

标签: wpf combobox binding datagrid

通过以下链接查看截图。

我已经搜索了半天,但找不到解决问题的方法。问题是:

当选择de comobox中的项目时(例如:RBS),我想在列' Beschrijving'中更改包含RBS的每一行的背景颜色。在datagrid中绿色en检查第一列中的复选框。

提前非常感谢你!

Screenshot

1 个答案:

答案 0 :(得分:0)

首先,我不知道你使用的语言是什么,我在这个例子中使用Powershell。

让我们将这个问题分解为逻辑步骤:

  1. 更改ComboBox值时,迭代所有行

  2. 在迭代时,使用ComboBox.Text Beschrijving 列匹配

  3. 如果匹配,请将复选框更改为True,更改行的颜色。

  4. 对于不匹配的项目,请将复选框更改为False并重置颜色。

  5. 肯定有一种更简单的方法可以做到这一点,但这是一个快速而肮脏的解决方案。

    ComboBox有一个SelectedIndexChanged事件,我们可以用它来确定是否选择了一个选项。

    最终简历的屏幕截图:ComboBox Select Highlight

    Function Edit-Row
    {
        param(
            [String] $BColor = "White", $FColor = "Black",
            [Object] $DataGridView,
            [Int32] $Row,
            [Switch] $TickCheckbox
        )
    
        $BeshrijvingColumnIndex = 2
        $CheckboxIndex          = 0
    
        # Row Background / Cell Color
        $DataGridView.Rows[$Row].DefaultCellStyle.BackColor = [System.Drawing.Color]::FromName($BColor)
    
        # Row Foreground / Text Color
        $DataGridView.Rows[$Row].DefaultCellStyle.ForeColor = [System.Drawing.Color]::FromName($FColor)
    
        # If Switch is Toggled, Tick Checkbox
        if($TickCheckbox)
        {
            $DataGridView.Rows[$Row].Cells[$CheckboxIndex].Value = $True
        }
    }
    
    $ComboBox = New-Object System.Windows.Forms.ComboBox
    $ComboBox.Items.Add("RBS")
    $ComboBox.Items.Add("KIU")
    $ComboBox.Items.Add("TBD")
    $ComboBox.Items.Add("TBO")
    $ComboBox.Items.Add("KIU")
    $ComboBox.Add_SelectedIndexChanged({
    
        $BeshrijvingColumnIndex = 2
        $CheckboxIndex          = 0
    
        for($row = 0; $row -lt $DataGridView.RowCount; $row++)
        {
            # Value of cell at Row[row].Cells[Beshrijving]
            $CellData = $DataGridView.Rows[$row].Cells[$BeshrijvingColumnIndex].Value
    
            if($CellData -match $ComboBox.Text)
            {
                Edit-Row `
                    -DataGridView $DataGridView `
                    -Row $row `
                    -BColor "Green" `
                    -FColor "White" `
                    -TickCheckbox
            }
            else
            {
                # Reset other rows back to initial state
                Edit-Row `
                    -DataGridView $DataGridView `
                    -Row $row
            }
        }
    })
    

    如果第2列包含选项中的字符串,此代码将突出显示一行。

      

    P.S:由于某些值,您可能不想使用-match关键字   包含类似的例如" TB"," TBD"," TBO"," TBL",如果   选项是" TB",它将匹配以" TB"开头的所有其他tokes。

相关问题