我是C#和WPF格式的新手。在我的程序中,我有一个包含文本的字符串数组,我想在画布中为数组中的每个字符串创建一个按钮。我已经使用了flex,我可以使用addChild命令将一些东西放入其他东西中,但我还没有想出如何在WPF中做到这一点。任何帮助都会很感谢,谢谢。
发布于 2010-07-18 15:01:15
我希望这能让你入门(未经测试!):
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/
发布于 2010-07-18 16:04:39
WPF具有使用绑定的能力:您可以直接将ItemsControl绑定到您的数组,然后告诉WPF如何使用模板显示每个项目,它会做到这一点。
<!-- 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
https://stackoverflow.com/questions/3274507
复制相似问题