I've tried putting children of both a ListView and an ItemsControl in rows and columns, by setting a grid with RowDefinitions and ColumnDefinitions as the ItemsPanel property.
However the child control always aligns to Row 1 and Column 1, when I put
<ItemsControl>
<ItemsControl.ItemsPanel>
<!-- Grid with rows & columns ... -->
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Grid.Row="4" Grid.Column="2" ... />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
How can I make this work? Thank you.
You should set the Grid.Row and Grid.Column attached properties of the container that wraps the root element of the ItemTemplate:
<ItemsControl x:Name="iccc">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
</Grid>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock>cell 2:2...</TextBlock>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Grid.Row" Value="1" />
<Setter Property="Grid.Column" Value="1" />
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
Set the ´Grid´ in the ´ItemTemplate´ rather than the ´ItemPanel´. See example here: http://www.wpf-tutorial.com/list-controls/itemscontrol/
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
PersonCollection = new ObservableCollection<Person>()
{
new Person() { FirstName = "John", LastName = "Doe" },
new Person() { FirstName = "Richard", LastName = "Bryson" },
new Person() { FirstName = "Bill", LastName = "Gates" },
new Person() { FirstName = "Adam", LastName = "Sandler" }
};
itemsControl.ItemsSource = PersonCollection;
}
public ObservableCollection<Person> PersonCollection { get; set; }
}
<ItemsControl x:Name="itemsControl">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Margin="0,0,0,5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding Path=FirstName}" />
<TextBlock Grid.Column="1" Text="{Binding Path=LastName}" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With