在代码后面的 C# WPF 中添加 UI 组件

And*_*rew 0 c# wpf code-behind

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

Kie*_*one 5

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>
Run Code Online (Sandbox Code Playgroud)

希望有帮助!

参考:

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