【发布时间】:2020-05-21 00:16:04
【问题描述】:
我正在编写一个 C# WPF 应用程序,用户可以在其中将测试架中的样本条码到应用程序中。
机架由行组成。每行包含多个样本。
每个示例都可以有一个示例详细信息列表(每次用户进行更改时的标识符和日期时间)。
这里有一张图片可以更好地可视化它:Picture of Rack
我想在 DataGrid 中表示这一点,用户可以在其中编辑网格中的每个样本。
我发现 XAML 相当困难。我已经设法使用代码隐藏(见下文)实现了我想要的,但我想在 XAML 中做到这一点。这是picture of output。
这可能吗?
谢谢
附加信息:
- 列数和行数是用户定义的,并且会因机架而异
- 行标题绑定到
Row类的RackPosition属性 - 列标题绑定到
Sample类的ColumnPosition - DataGridCell 内的文本绑定到
History[0].Identifier - Caliburn Micro 将用于处理用户对样本的更新
我的代码:
类:
public class Rack
{
public string Name { get; set; }
public DateTime DateCreated { get; set; }
public List<Row> Rows { get; set; } = new List <Row>();
}
public class Row
{
public int RackPosition { get; set; }
public string Name { get; set; }
public List<Sample> Samples { get; set; } = new List <Sample>();
}
public class Sample
{
public int ColumnPosition { get; set; }
public List<SampleDetails> History { get; set; } = new List <SampleDetails>();
}
public class SampleDetails
{
public string Identifier { get; set; }
public DateTime TimeStamp { get; set; }
}
数据网格:
<DataGrid x:Name="MainDG" AutoGenerateColumns="False" CanUserAddRows="False">
<DataGrid.RowHeaderStyle>
<Style TargetType="{x:Type DataGridRowHeader}">
<Setter Property="Content" Value="{Binding RackPosition}"/>
</Style>
</DataGrid.RowHeaderStyle>
</DataGrid>
代码背后:
public Rack CurrentRack { get; set; }
public MainWindow()
{
InitializeComponent();
SetupDataGrid();
}
//Gets a dummy rack
public Rack GetExampleRack()
{
Rack rack = new Rack();
for (int i = 0; i < 4; i++)
{
Row row = new Row();
row.Samples = new List<Sample>();
row.RackPosition = i;
for (int j = 0; j < 5; j++)
{
row.Samples.Add(new Sample { ColumnPosition = j });
}
rack.Rows.Add(row);
}
SampleDetails testSample1 = new SampleDetails { Identifier = "Test ID 1", TimeStamp = DateTime.Now };
SampleDetails testSample2 = new SampleDetails { Identifier = "Test ID 2", TimeStamp = DateTime.Now };
rack.Rows[0].Samples[0].History.Add(testSample1);
rack.Rows[1].Samples[3].History.Add(testSample2);
return rack;
}
private void SetupDataGrid()
{
MainDG.Columns.Clear();
CurrentRack = GetExampleRack();
foreach (var sample in CurrentRack.Rows[0].Samples)
{
var sampleIndex = CurrentRack.Rows[0].Samples.IndexOf(sample);
DataGridTemplateColumn col = new DataGridTemplateColumn();
col.Header = sampleIndex;
FrameworkElementFactory textBox = new FrameworkElementFactory(typeof(TextBox));
var binding = new Binding();
binding.BindingGroupName = ".";
binding.Path = new PropertyPath($"Samples[{sampleIndex}].History[0].Identifier");
textBox.SetBinding(TextBox.TextProperty, binding);
DataTemplate dt = new DataTemplate { VisualTree = textBox };
dt.Seal();
col.CellTemplate = dt;
MainDG.Columns.Add(col);
}
MainDG.ItemsSource = CurrentRack.Rows;
}
【问题讨论】:
-
为什么不使用multidimensional-arrays?
-
单个样品架中的所有行的样本数是否相等?
-
@Keith 是的。 Cfun 我会调查的。谢谢