[英]Binding a DataGrid*Column to data in code-behind
我想在后面的代码中将DataGrid * Column (在这种情况下,是DataGridTextBox ) 绑定到其数据。 这是因为,根据CheckBox的IsClicked属性,该列需要绑定到不同的集合。
解决方案,如这一个都指向以下排序的代码:
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,所以我也已经做到了(编辑原始代码),但仍然无济于事。 整个列仍绑定到集合的第一个元素。
弄清楚了。 在这种情况下,必须定义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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.