Hi, I'm new to C# and WPF format. In my program, I have an array of strings with text, and I want to create a button in the canvas for each string in the array. I've used flex, and in that i can use the addChild command to put something in something else, but I haven't figured out how to do it in WPF yet. Any help would be appreciated, thanks.
A:
I hope this can get you started (untested!):
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, ... );
}
A more advanced technique would let you sync the UI to the contents of your array.
I highly recommend the book "WPF Unleashed" to learn WPF. http://www.adamnathan.net/wpf/
Tom Sirgedas
2010-07-18 07:01:14
I ended up using myCanvas.Children.Add(sideBarButtons[i]);for some reason myCanvas.addChild didn't work at all.Thanks for the help!
Andrew
2010-07-18 16:34:18
+4
A:
WPF is streams ahead with the ability to use Binding: you can bind an ItemsControl to your array directly, then tell WPF how to display each item with a Template and it will do it.
<!-- 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>
Hope that helps!
Reference:
http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.aspx
Kieren Johnstone
2010-07-18 08:04:38
myCanvas.Children.Add(sideBarButtons[i]); is what I ended up using, and it worked like I wanted.
Andrew
2010-07-18 16:34:53