将DataGrid*Column绑定到代码后置中的数据

本文关键字:数据 代码 DataGrid Column 绑定 | 更新日期: 2023-09-27 18:02:53

我想绑定一个DataGrid*Column(在这种特殊情况下,一个DataGridTextBox)到它的数据在代码后面。这是因为,根据CheckBox的IsClicked属性,Column需要绑定到不同的集合。

像这样的解决方案都指向以下类型的代码:
var binding = new Binding("X");
XColumn.Binding = binding;
现在,我已经在程序的其他部分成功地使用了这种代码,只是没有使用DataGrid*Column。然而,对于列,这并不像预期的那样工作,因为实际上列的所有行都表示集合的第一个元素的x值。当我编辑任何单元格并且它们都被更改时,这一点得到了证实,这意味着它们都绑定到集合的同一单个元素,而不是作为一个整体绑定到集合。

相关代码如下:

//This is called whenever the CheckBox EqualToResults is clicked
void ControlBindings()
{
    //only showing for (.IsChecked == true), but the other case is similar
    //and presents the same problems
    if (EqualToResults.IsChecked == true)
    {
        var cable = DataContext as NCable;
        //This is the DataGrid object
        Coordinates.ItemsSource = cable;
        var binding = new Binding("X");
        binding.Source = cable.Points;
        //XColumn is the DataGridTextColumn
        XColumn.Binding = binding;
    }
}

应该是相关的,下面是NCable类的相关代码。

public class NCable : DependencyObject, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    public ObservableCollection<NPoint> Points;
    public static DependencyProperty PointsProperty = DependencyProperty.Register("Points", typeof(ICollectionView), typeof(NCable));
    public ICollectionView IPointCollection
    {
        get { return (ICollectionView)GetValue(PointsProperty); }
        set { SetValue(PointsProperty, value); }
    }
    public NCable(string cableName)
    {
        Points = new ObservableCollection<NPoint>();
        for (int i = 0; i < 11; i++)
            Points.Add(new NPoint(1,1));
        IPointCollection = CollectionViewSource.GetDefaultView(Points);
    }
}

EDIT 13/05:我在某个地方看到,在这种情况下还必须设置DataGrid的ItemsSource,所以我也这样做了(编辑了原始代码),但仍然无济于事。整个列仍然绑定到集合的第一个元素。

将DataGrid*Column绑定到代码后置中的数据

明白了。在这种情况下,必须定义DataGrid.ItemsSource(根据oP中的编辑),但必须保留未定义的binding.Source。因此,功能代码是

void ControlBindings()
{
    if (EqualToResults.IsChecked == true)
    {
        var cable = DataContext as NCable;
        Coordinates.ItemsSource = cable;
        var binding = new Binding("X");
        //REMOVE binding.Source = cable.Points;
        XColumn.Binding = binding;
    }
}