如何在WPF中以编程方式将滚动条添加到网格中
本文关键字:滚动条 添加 网格 方式 编程 WPF | 更新日期: 2024-10-24 13:14:11
我在xaml文件中有以下网格:
<Grid x:Name="gridPMP" HorizontalAlignment="Left" Height="285" Margin="23,116,0,-330" Grid.Row="1" VerticalAlignment="Top" Width="1238"/>
该网格以编程方式填充了以下代码。cs:
public void loadPMPTable()
{
gridPMP.Children.Clear();
gridPMP.RowDefinitions.Clear();
gridPMP.ColumnDefinitions.Clear();
MetodosAux aux = new MetodosAux();
String s = problemName.Content.ToString();
String listaPath = "./DataSaved/" + s + "/ListaDeMateriales.txt";
String arbolPath = "./DataSaved/" + s + "/ArbolDeMateriales";
String RIPath = "./DataSaved/" + s + "/RegistroInventarios.txt";
int cols = NumValue + 1;
int rows = aux.numeroLineasFichero(listaPath) + 1;
FileStream fs = new FileStream(listaPath, FileMode.Open, FileAccess.Read);
System.IO.StreamReader file = new System.IO.StreamReader(fs);
String linea;
for (int x = 0; x < cols; x++)
{
ColumnDefinition CD = new ColumnDefinition();
if (x==0)
{
CD.Width = new System.Windows.GridLength(120);
}
else
{
CD.Width = new System.Windows.GridLength(30);
}
//CD.Width = GridLength.Auto;
gridPMP.ColumnDefinitions.Add(CD);
}
for (int y = 0; y < rows; y++)
{
RowDefinition r = new RowDefinition();
//r.Height = GridLength.Auto;
r.Height= new System.Windows.GridLength(30);
gridPMP.RowDefinitions.Add(r);
}
for (int x = 0; x < cols; x++)
{
for (int y = 0; y < rows; y++)
{
if ((y == 0) && (x == 0)) //y=row index, x=column index
{
TextBox t = new TextBox();
t.Width = 170;
t.IsReadOnly = true;
t.Text = "Elemento/Día";
t.FontWeight = FontWeights.UltraBold;
Grid.SetColumn(t, x);
Grid.SetRow(t, y);
gridPMP.Children.Add(t);
}
else if ((y == 0) && (x >= 1))
{
TextBox t = new TextBox();
t.Width = 170;
t.IsReadOnly = true;
t.Text = x.ToString();
t.FontWeight = FontWeights.UltraBold;
Grid.SetColumn(t, x);
Grid.SetRow(t, y);
gridPMP.Children.Add(t);
}
else if (x == 0)
{
TextBox t = new TextBox();
t.Width = 170;
t.IsReadOnly = true;
linea = file.ReadLine();
t.Text = linea;
t.FontWeight = FontWeights.DemiBold;
Grid.SetColumn(t, x);
Grid.SetRow(t, y);
gridPMP.Children.Add(t);
}
else
{
TextBox tb = new TextBox();
tb.PreviewTextInput += textBoxValidator;
tb.Width = 170;
tb.Text = "0";
Grid.SetColumn(tb, x);
Grid.SetRow(tb, y);
gridPMP.Children.Add(tb);
}
}
}
file.Close();
fs.Close();
}//end loadPMPTable()
列和行的数量会根据某些文件的结构而变化。因此,当有超过8行时,网格不会显示数据,因为没有足够的空间。这就是为什么我想让网格可以滚动。如何通过编程或从xaml文件中执行此操作?我从xaml文件中尝试过,但没有成功。
您可以将其放入ScrollViewer
:中
<ScrollViewer>
<Grid x:Name="gridPMP" HorizontalAlignment="Left" Height="285" Grid.Row="1" VerticalAlignment="Top"/>
</ScrollViewer>