[英]Want to add textblock in grid dynamically on button click
我有10行3列的網格,我想在該網格上添加TextBlock。 當用戶單擊水平按鈕時,文本塊應添加到水平網格單元中;如果單擊垂直按鈕,則應添加垂直網格單元中。 一鍵添加一個文本塊。 以下是我的代碼:
<Button Content="Add Hrzntly" Grid.Row="0" Grid.Column="1" Width="100" Height="30" Click="Button_Click"/>
<Button Content="Add Vrtcly" Grid.Row="1" Grid.Column="0" Width="100" Height="30" Click="Button_Click_1"/>
<Grid ShowGridLines="True" x:Name="gridChart" Grid.Row="1" Grid.Column="1">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
</Grid>
private void Button_Click(object sender, RoutedEventArgs e)
{
var newTextBox = new TextBox();
newTextBox.Width = 100;
newTextBox.Height = 30;
newTextBox.Text = "FTB solutions";
// here set new textbox parameters
gridChart.Children.Add(newTextBox);
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
var newTextBox = new TextBlock();
newTextBox.Width = 100;
newTextBox.Height = 30;
newTextBox.Text = "FTB solutions";
// here set new textbox parameters
gridChart.Children.Add(newTextBox);
}
您需要指定TextBox
正在進行哪一Row
。
newTextBox.SetValue(Grid.RowProperty, number);
是要創建清單嗎? 如果是這樣,則WPF中已經內置了支持此功能的控件(無需重新發明)。
例
XAML:
<ListBox x:Name="myListBox Width="200" Margin="10"/>
xaml.cs:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
var listBoxItem = new ListBoxItem();
listBoxItem.Content = "this is a new item";
myListBox.Items.Add(listBoxItem);
}
雖然,處理這樣的事件有點“ Winform風格”。 使用WPF,您可能希望使用MVVM,並通過ViewModel(而不是后面的代碼)來處理集合的添加/更新。 獲得WPF的更多經驗后,請查看MVVM。
供參考,請參閱: 如何通過單擊沒有任何代碼隱藏的按鈕將列表框中的項目添加到列表中?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.