【问题标题】:Creating a textbox in xaml through xaml.cs code通过 xaml.cs 代码在 xaml 中创建文本框
【发布时间】:2016-12-06 13:23:11
【问题描述】:

我想通过一个按钮单击循环中的 .xaml.cs 文件(可能),在 xaml 文件中创建文本框。我已经计算了每个文本框出现在面板中的边距,但不知道如何绑定代码。 Here's the image of the xaml design view and what I'm trying to achieve. The window will have one textbox for choices appear and the loop will create another and another each time the add choice button is clicked.

有人可以帮忙吗?我只是在学习wpf。谢谢

【问题讨论】:

  • 绑定代码是什么意思?推荐一本书Applications = Code + Markup
  • @LeiYang 我的意思是 .xaml.cs 文件中的代码应该在 .xaml 文件中创建相应的操作
  • 那你有什么尝试
  • 已搜索但找不到任何关于从 cs 代码创建新组件的信息。老实说,不知道如何去做。任何提示或示例或任何内容都会有所帮助
  • @LeiYang 您提供的链接不是完整的书。一定要买吗?

标签: c# wpf visual-studio xaml


【解决方案1】:

假设 绑定代码 您的意思是如何将TextBox 添加到面板中。为此,您需要将文本框添加到面板的 Children 属性中。

如果您需要在初始化表单时执行此操作,只需将代码放在表单构造函数中的 InitializeComponent(); 之后即可。

这是一个如何以编程方式执行此操作的示例,响应点击事件:

Xaml:

<StackPanel Name="pn_Content" Orientation="Vertical">
    <Button Click="btn_Add_TextBox_Click">Add Textbox</Button>
</StackPanel>

C#:

private void btn_Add_TextBox_Click(object sender, RoutedEventArgs e) {
   TextBox tb = new TextBox();
   tb.Height = 23;
   tb.Width = 100;
   pn_Content.Children.Add(tb);
}

就是这样。

【讨论】:

  • 非常感谢,我只是需要那个小例子来指导:] 真的很有帮助
【解决方案2】:

首先,将所有当前文本框放入一个容器中,例如名为 stackPanel 的堆栈面板。 然后将您的控件添加到面板的子项中:

stackPanel.Children.Add(new TextBox { Text = "TextBox" });

请参考以下问题:

WPF: How to dynamically Add Controls in dynamically created WPF Window

Adding child controls in Stackpanel WPF C#

【讨论】:

    猜你喜欢
    • 2020-09-24
    • 2010-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多