首页 文章

WPF:选择另一个单元格时更新数据网格中的单元格

提问于
浏览
0

我们有一个由DataGridTemplateColumns组成的DataGrid .
一些列包含简单的TextBlocks,而其他列使用ComboBoxes .

当用户单击带有ComboBox的单元格时,我们需要使用单击的ComboBox的当前值更新同一行中的TextBlock .
当组合框选择的值发生变化时,这很容易做到(绑定到组合框的属性更新绑定到texblock的属性,当组合框仅在选择组合框单元时弄清楚如何做到这一点 .
Datagrid上的SelectionUnit是CellOrRowHeader .

我一直在努力尝试从SelectedCellsChangedEvent处理程序等中提取DataGrid.CurrentCell中的值,但没有成功 .
为什么在选择数据网格单元格时获取当前值如此困难?!
任何指针将不胜感激......

1 回答

  • 0

    不知道哪里出了问题,但这对我有用 . MyRowItem 只是一个实现 INotifyPropertyChanged 的随机类 .

    它需要一些额外的布线来往返值,这可能会变得奇怪 .

    private void DataGrid_SelectedCellsChanged(object sender, 
        SelectedCellsChangedEventArgs e)
    {
        //  For multiselection, e.AddedCells is a collection of all 
        //  currently selected cells as DataGridCellInfo
    
        var currentCell = (sender as DataGrid).CurrentCell;
    
        var row = currentCell.Item as MyRowItem;
    
        //  Note that we're using the column header as a magic string.
        //  We could use the Tag property to make this slightly less 
        //  fragile. 
        switch (currentCell.Column.Header.ToString())
        {
            case "Combo One":
                row.TextCol = row.ComboColOne;
                break;
    
            case "Combo Two":
                row.TextCol = row.ComboColTwo;
                break;
        }
    }
    

    XAML

    <DataGrid 
        ItemsSource="{Binding Path=ItemCollection}" 
        SelectionUnit="CellOrRowHeader"
        AutoGenerateColumns="False" 
        SelectedCellsChanged="DataGrid_SelectedCellsChanged"
        >
        <DataGrid.Columns>
            <DataGridTextColumn 
                Header="Text" 
                Binding="{Binding TextCol}" 
                Width="120"
                />
            <DataGridComboBoxColumn
                Header="Combo One"
                ItemsSource="{Binding Source={x:Static local:MyRowItem.BValues}}"
                SelectedItemBinding="{Binding ComboColOne}"
                Width="120"
                />
            <DataGridComboBoxColumn
                Header="Combo Two"
                ItemsSource="{Binding Source={x:Static local:MyRowItem.CValues}}"
                SelectedItemBinding="{Binding ComboColTwo}"
                Width="120"
                />
        </DataGrid.Columns>
    </DataGrid>
    

相关问题