2010-07-18 17 views
0

我是C#和WPF格式的新手。在我的程序中,我有一個帶有文本的字符串數組,我想在畫布中爲數組中的每個字符串創建一個按鈕。我已經使用了flex,並且我可以使用addChild命令將某些東西放入其他東西中,但我還沒有想出如何在WPF中執行此操作。任何幫助將不勝感激,謝謝。在C#WPF中添加UI組件

回答

-1

我希望這可以讓你開始(未經測試!):

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, ...); 
} 

更先進的技術將讓你同步的UI您數組的內容。

我強烈推薦本書「WPF Unleashed」學習WPF。 http://www.adamnathan.net/wpf/

+0

我最終使用myCanvas.Children.Add(sideBarButtons [I]); 由於某種原因myCanvas.addChild根本無法使用。 感謝您的幫助! – Andrew 2010-07-18 16:34:18

4

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

+0

myCanvas.Children.Add(sideBarButtons [i]);就是我最終使用的,它像我想要的那樣工作。 – Andrew 2010-07-18 16:34:53