简体   繁体   中英

Want to add textblock in grid dynamically on button click

I have grid with 10 rows and 3 columns and I want to add TextBlock on that grid. When User clicks the horizontal button then text block should add in horizontal grid cell and if clicks on vertical button then add in vertical grid cell. on one click one textblock will be added. following is my code:

<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);

Is to to create a list? if so, there are already built in controls within WPF that support this (no need to re-invent).

Example

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);
}

Though, handling events like this is a bit more 'Winform-ish'. With WPF, you would want to use MVVM, and handle the adding/updating of collections via a ViewModel (rather than code behind). Please look into MVVM once you have gained more experience with WPF.

For reference, see: How can I add items from a listbox to a list by clicking a button without any codebehind?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM