[英]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.