Добавление компонентов пользовательского интерфейса в C # WPF в коде позади - PullRequest
0 голосов
/ 18 июля 2010

Я новичок в C # и формате WPF. В моей программе у меня есть массив строк с текстом, и я хочу создать кнопку на холсте для каждой строки в массиве. Я использовал flex, и в этом я могу использовать команду addChild, чтобы поместить что-то в что-то еще, но я еще не понял, как это сделать в WPF. Любая помощь будет оценена, спасибо.

Ответы [ 2 ]

4 голосов
/ 18 июля 2010

WPF впереди потоков с возможностью использовать Binding: вы можете напрямую привязать 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 голосов
/ 18 июля 2010

Надеюсь, это поможет вам начать (не проверено!):

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 Unleashed" для изучения WPF.http://www.adamnathan.net/wpf/

...