[英]How to dynamically create and modify a new Grid row elements?
我剛剛啟動一個新的WPF應用程序。 我有一個網格,想要動態創建行(例如,按下按鈕),然后在此行內創建TextView / ProgressBar。
我已經搜索過如何以編程方式創建網格行。 但是在每種解決方案中,我都無法訪問其中的內容,它變得毫無用處。
<Grid x:Name="MainGrid">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Button x:Name="AddLineButton" Content="Click to add a new line" Click="AddLineButton_Click"/>
<Grid x:Name="beGrid" Grid.Row="1">
<!-- I need my new rows here -->
</Grid>
</Grid>
int i = 0; //nb of rows
private void AddLineButton_Click(object sender, RoutedEventArgs e)
{
Create_line();
i++;
}
private void Create_line()
{
RowDefinition gridRow = new RowDefinition();
gridRow.Height = new GridLength(1, GridUnitType.Star);
beGrid.RowDefinitions.Add(gridRow);
StackPanel stack = new StackPanel();
stack.Orientation = Orientation.Horizontal;
TextBlock textBlock = new TextBlock();
textBlock.Text = "Question";
textBlock.Name = "Test" + i.ToString();
stack.Children.Add(textBlock);
beGrid.Children.Add(stack);
Grid.SetRow(stack, i);
}
我無法訪問先前創建的元素。
回答后:
private void Create_line()
{
RowDefinition gridRow = new RowDefinition();
gridRow.Height = new GridLength(1, GridUnitType.Star);
beGrid.RowDefinitions.Add(gridRow);
StackPanel stack = new StackPanel();
stack.Orientation = Orientation.Horizontal;
TextBlock textBlock = new TextBlock();
textBlock.Text = "Question";
textBlock.Name = "Test" + i.ToString();
RegisterName(textBlock.Name, textBlock);
stack.Children.Add(textBlock);
beGrid.Children.Add(stack);
Grid.SetRow(stack, i);
}
要獲取創建的TextBlock: var text = (TextBlock)FindName("Test"+i.ToString());
您可以將所有創建的StackPanel存儲在一個列表中。
private void AddLineButton_Click(object sender, RoutedEventArgs e)
{
Create_line();
}
List<StackPanel> items;
private void Create_line()
{
RowDefinition gridRow = new RowDefinition();
gridRow.Height = new GridLength(1, GridUnitType.Star);
beGrid.RowDefinitions.Add(gridRow);
StackPanel stack = new StackPanel();
stack.Orientation = Orientation.Horizontal;
int i = items.Count + 1;
TextBlock textBlock = new TextBlock();
textBlock.Text = "Question";
textBlock.Name = "Test" + i.ToString();
stack.Children.Add(textBlock);
beGrid.Children.Add(stack);
Grid.SetRow(stack, items.Count);
items.Add(stack);
}
您可以按索引訪問任何previos面板,例如items[0]
,並從Children
屬性中獲取元素: items[0].Children[0] as TextBlock
像這樣手動創建控件實際上不是WPF方式...
最好的方法是定義一個項目類,其中包含要顯示/編輯的每個值的屬性。
然后在Window中創建這些項目的ObservableCollection
(因為您將通過單擊按鈕手動添加項目),並將其設置為ItemsControl
控件的ItemsSource
屬性。 DataTemplate
用於定義確切的控件以顯示控件中的每個項目,這些控件將綁定到項目的屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.