我想將 Array 系結到一個 4 列的 DataGrid 并更新資料。這可能嗎?
如果不能實作,我需要如何修改它?
對于自動更新,似乎我們可以系結到一些具有可編輯值的物件集合是為該專案定義一個類。但我不知道該怎么做。
public partial class MainWindow : Window
{
int X=18;
public MainWindow()
{
InitializeComponent();
int[] arr = new int[] { 61, 61, 61, 61, 61, 20, 30, 40, 50, 100, 200, 300, 400, 500, 0, 0, 0, 0, 0, 18, 23, 65, 41, 22, 91, 64, 33, 18, 44, 63, 91, 26, 32, 61, 83, 91, 26, 32, 91, 91, 91, 91 };
DataGrid dataGrid = new DataGrid();
dataGrid.AutoGenerateColumns = false;
dataGrid.ItemsSource = arr.ToList();
for (int i = 1; i < 5; i )
{
DataGridTemplateColumn column = new DataGridTemplateColumn();
column.Header = "Value" i;
DataTemplate cellTemplate = new DataTemplate();
FrameworkElementFactory textBlock = new FrameworkElementFactory(typeof(TextBlock));
textBlock.SetBinding(TextBlock.TextProperty, new Binding("."));
cellTemplate.VisualTree = textBlock;
column.CellTemplate = cellTemplate;
DataTemplate cellEditingTemplate = new DataTemplate();
FrameworkElementFactory textBox = new FrameworkElementFactory(typeof(TextBox));
textBox.SetBinding(TextBox.TextProperty, new Binding("."));
cellEditingTemplate.VisualTree = textBox;
column.CellEditingTemplate = cellEditingTemplate;
dataGrid.Columns.Add(column);
}
canvas.Children.Add(dataGrid);
Canvas.SetLeft(dataGrid, X);
}
}
結果:

我想要這樣的結果:
61, 61, 61, 61, 61,
20, 30, 40, 50, 100,
200, 300, 400, 500, 0,
0, 0, 0, 0, 18,
uj5u.com熱心網友回復:
您只能使用陣列來完成。請注意,這ItemsControl.ItemsSource是型別IEnumerable:您可以將陣列直接分配給此屬性。
這里的ToList()呼叫是多余的。
也用aDataGridTextColumn代替了DataGridTemplateColumn取消對單元格模板的修改,只添加了一個TextBlock.
DataGrid將其IEnumerable源集合的每個專案視為一行。這就是為什么您的表格看起來如此:每個數字都寫入一個新行。對每一列重復此操作。
這意味著,您必須更改資料結構以適應每項到一行規則。因為您有五列,所以您必須構造陣列以提供 5 元組(五元組)元素 - 每個五元組元素為一行。
您可以通過使用鋸齒狀陣列(即陣列陣列)來實作這一點。
然后在配置 時DataGrid.Columns,您必須使用系結索引器才能從陣列(行資料)中提取列的值。
“對于自動更新 [...]”
您必須知道使用陣列時沒有“自動更新”。如果要在應用程式運行時修改陣列(動態資料),則必須使用ObservableCollection<int[]>代替int[][]鋸齒狀陣列。
主視窗.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Loaded = onl oaded;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
int[][] numbers =
{
new[] { 61, 61, 61, 61, 61 },
new[] { 20, 30, 40, 50, 100 },
new[] { 200, 300, 400, 500, 0 }
};
this.NumbersDataGrid.ItemsSource = numbers;
}
}
主視窗.xaml
<Window>
<DataGrid x:Name="NumbersDataGrid"
AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Value1"
Binding="{Binding [0]}" />
<DataGridTextColumn Header="Value2"
Binding="{Binding [1]}" />
<DataGridTextColumn Header="Value3"
Binding="{Binding [2]}" />
<DataGridTextColumn Header="Value4"
Binding="{Binding [3]}" />
<DataGridTextColumn Header="Value4"
Binding="{Binding [4]}" />
</DataGrid.Columns>
</DataGrid>
</Window>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/399873.html
上一篇:WPFViewport3DTextureCoordinates
下一篇:使用Python兩次溢位列
