对于每次单击按钮,我需要将列表内容添加到WPF中的数据网格视图的新行。
以下是代码,但它没有给出确切的行为。
public class DisplayTable
{
public int AnalyteId { get; set; }
public int UnitCode { get; set; }
public int ReferenceValue { get; set; }
}
DisplayTable d = new DisplayTable();
List<DisplayTable> list = new List<DisplayTable>();
private void btnAddAnalyte_Click(object sender, RoutedEventArgs e)
{
foreach (CheckBox item in this.AnalyteLitst.Items)
{
if (item.IsChecked == true)
{
d.AnalyteId = 1;
}
}
foreach (CheckBox unit in this.UnitsList.Items)
{
if (unit.IsChecked == true)
{
d.UnitCode = 12;
}
}
list.Add(d);
dataGrid.AutoGenerateColumns = true;
dataGrid.IsReadOnly = false;
dataGrid.RowHeight = 30;
dataGrid.ColumnWidth = 100;
dataGrid.ItemsSource = list;
dataGrid.CanUserAddRows = true;
}
答案 0 :(得分:0)
在视图的构造函数中设置ItemsSource
一次的DataGrid
。同时将其设置为ObservableCollection<DisplayTable>
并在事件处理程序中向此对象添加新对象:
ObservableCollection<DisplayTable> list = new ObservableCollection<DisplayTable>();
public MainWindow()
{
InitializeComponent();
dataGrid.AutoGenerateColumns = true;
dataGrid.IsReadOnly = false;
dataGrid.RowHeight = 30;
dataGrid.ColumnWidth = 100;
dataGrid.ItemsSource = list;
dataGrid.CanUserAddRows = true;
}
private void btnAddAnalyte_Click(object sender, RoutedEventArgs e)
{
DisplayTable d = new DisplayTable();
foreach (CheckBox item in this.AnalyteLitst.Items)
{
if (item.IsChecked == true)
{
d.AnalyteId = 1;
}
}
foreach (CheckBox unit in this.UnitsList.Items)
{
if (unit.IsChecked == true)
{
d.UnitCode = 12;
}
}
list.Add(d);
}