我想將一個DataGrid *列(在這種特殊情況下,一個DataGridTextBox)綁定到代碼隱藏中的數據。這是因爲,根據CheckBox的IsClicked屬性,Column需要綁定到不同的集合。將DataGrid *列綁定到代碼隱藏的數據
解決方案,如this one都指向下面的代碼排序:
var binding = new Binding("X");
XColumn.Binding = binding;
現在,我已經利用這種在我的成功程序的其它部分的代碼,只是沒有用DataGrid *列。但是,對於列,這不能按預期工作,因爲實際上列的所有行都顯示集合中第一個元素的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時在這種情況下,所以我做到了這一點,以及(編輯原碼),但仍無濟於事。整個列仍然綁定到集合的第一個元素。