繁体   English   中英

想要在单击按钮时在网格中动态添加文本块

[英]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.

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