[英]How to add a scrollbar to a grid programmatically in WPF?
我在 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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.