Search code examples
c#wpfwrappanelitemsource

WPF Best way to add generated Content


currently do it like this:

<Grid VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Grid.Column="2">
  <ListBox Name="lb_right"  Background="Red">
    <ListBox.Resources>
      <DataTemplate DataType="{x:Type local:Textfeld_Template}">
        <WrapPanel HorizontalAlignment="Stretch">
          <Label Content="{Binding name}"></Label>
          <TextBox Text="{Binding text}" HorizontalAlignment="Stretch"></TextBox>
          <Label Foreground="Red" IsEnabled="{Binding Pflicht}">Pflichtfeld!</Label>
        </WrapPanel>
      </DataTemplate>

      <DataTemplate DataType="{x:Type local:Datefeld_Template}">
        <WrapPanel HorizontalAlignment="Stretch">
          <Label Content="{Binding name}"></Label>
          <DatePicker HorizontalAlignment="Stretch" Text="{Binding zeit,StringFormat='dd.MMM.yyyy'}"></DatePicker>
          <Label Foreground="Red" IsEnabled="{Binding Pflicht}">Pflichtfeld!</Label>
        </WrapPanel>
      </DataTemplate>
    </ListBox.Resources>
  </ListBox>
</Grid>

For filling I use

ObservableCollection<Object> t = new ObservableCollection<Object>();

and set it to the Itemsource of listview, works fine, but, it is a listview, is there a Element with Itemsource like Wrappanel?


Solution

  • Ok thanks, i found the Solution: ItemsControl (never used/saw it before)

    <ItemsControl Name="lb_right"  Background="Red">
    
    
                        <ItemsControl.Resources>
                    <DataTemplate DataType="{x:Type local:Textfeld_Template}">
                                <WrapPanel HorizontalAlignment="Stretch">
                        <Label Content="{Binding name}"></Label>
                                    <TextBox Text="{Binding text}" HorizontalAlignment="Stretch"></TextBox>
                                <Label Foreground="Red" IsEnabled="{Binding Pflicht}">Pflichtfeld!</Label>
                            </WrapPanel>
                        </DataTemplate>
    
                        <DataTemplate DataType="{x:Type local:Datefeld_Template}">
                            <WrapPanel HorizontalAlignment="Stretch">
                                <Label Content="{Binding name}"></Label>
                                    <DatePicker HorizontalAlignment="Stretch" Text="{Binding zeit,StringFormat='dd.MMM.yyyy'}"></DatePicker>
                                <Label Foreground="Red" IsEnabled="{Binding Pflicht}">Pflichtfeld!</Label>
                            </WrapPanel>
                        </DataTemplate>
                        </ItemsControl.Resources>
                    </ItemsControl>