将DataGrid *列绑定到代码隐藏中的数据

时间:2014-05-12 20:49:27

标签: c# wpf binding datagrid

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

this one之类的解决方案都指向以下类型的代码:

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);
    }
}

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

1 个答案:

答案 0 :(得分:0)

想出来。在这种情况下,必须定义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;
    }
}