首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在代码隐藏中添加C# WPF中的UI组件

在代码隐藏中添加C# WPF中的UI组件
EN

Stack Overflow用户
提问于 2010-07-18 13:58:52
回答 2查看 4.1K关注 0票数 0

我是C#和WPF格式的新手。在我的程序中,我有一个包含文本的字符串数组,我想在画布中为数组中的每个字符串创建一个按钮。我已经使用了flex,我可以使用addChild命令将一些东西放入其他东西中,但我还没有想出如何在WPF中做到这一点。任何帮助都会很感谢,谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-07-18 15:01:15

我希望这能让你入门(未经测试!):

代码语言:javascript
运行
复制
foreach ( var s in textArray )
{
  Button b = new Button();
  //set button width/height/text
  ...
  myCanvas.AddChild( b );

  // position button on canvas (set attached properties)
  Canvas.SetLeft( b, ... ); // fill in the ellipses
  Canvas.SetTop( b, ... );
}

一种更高级的技术可以让用户界面与数组的内容同步。

我强烈推荐"WPF释放“这本书来学习WPF。http://www.adamnathan.net/wpf/

票数 -1
EN

Stack Overflow用户

发布于 2010-07-18 16:04:39

WPF具有使用绑定的能力:您可以直接将ItemsControl绑定到您的数组,然后告诉WPF如何使用模板显示每个项目,它会做到这一点。

代码语言:javascript
运行
复制
<!-- ItemsControl is a customisable way of creating a UI element for each item in a
collection.  The ItemsSource property here means that the list of items will be     selected
from the DataContext of the control: you need to set the DataContext of this control, or
the window it is on, or the UserControl it is in, to your array -->

<ItemsControl ItemsSource="{Binding}">

    <!-- The Template property specifies how the whole control's container should look -->
    <ItemsControl.Template>
        <ControlTemplate TargetType="{x:Type ItemsControl}">
            <ItemsPresenter/>
        </ControlTemplate>
    </ItemsControl.Template>

    <!-- The ItemsPanel tells the ItemsControl what kind of panel to put all the items in; could be a StackPanel, as here; could also be a Canvas, Grid, WrapPanel, ... -->
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Vertical"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>

    <!-- The ItemTemplate property tells the ItemsControl what to output for each item in the collection.  In this case, a Button -->
    <ItemsControl.ItemTemplate>
        <DataTemplate>

            <!-- See here the Button is bound with a default Binding (no path): that means the Content be made equal to the item in the collection - the string - itself -->
            <Button Content="{Binding}" Width="200" Height="50"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

希望这能有所帮助!

参考资料:

http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.aspx

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3274507

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档