Since nearly all elements of my page are auto sized the following changes to the above solution helped.
Page containing grid of stackpanels:
public MainPage()
{
InitializeComponent();
}
private void FillGridWithItems()
{
//Row and ColumnDefinitions
for (int row = 0; row < 5; row++)
{
for (int col = 0; col < 7; col++)
{
var item = new MyStackPanel(children)
Grid.SetColumn(item, col);
Grid.SetRow(item, row);
grid.Children.Add(item);
}
}
Loaded+=PageLoaded;
}
/// When page is loaded, ActualHeight of elements are calculated for sure.
private void PageLoaded(object sender, RoutedEventArgs e)
{
foreach (var child in grid.Children)
{
var item = child as MyStackPanel;
if (item != null)
{
item.FillInData();
}
}
}
/// Used instead of constructor, cause a parameter is sent to this page.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
FillGridWithItems()
}
MyStackPanel:
private readonly List<string> _items;
public MyStackPanel(List<string> items)
{
_items = items;
var behavior = new MyBehavior();
behavior.SetBinding(MyBehavior.ShowDetailsCommandProperty, new Binding
{
Path = new PropertyPath("ShowDetailsCommand")
});
Interaction.GetBehaviors(this).Add(behavior);
}
public void FillInData()
{
foreach (string item in _items)
{
var block = new Button();
block.Click += ItemClick;
this.Children.Add(block);
}
}
MyBehaviour (just the changed Part)
...
private void OnLayoutUpdated(object sender, object o)
{
var container = (Grid) AssociatedObject.Parent;
if (container == null) return;
var height = container.RowDefinitions[Grid.GetRow(AssociatedObject)].ActualHeight;
// ... The same as above
}
....
I didn't implement the ShowDetailsCommand yet, so I can't say if the RelayCommand works as intended, but why should it not ;)
There are also some modifications need to be done for windows store, like using the WinRtBehaviors library, that can all be solved by googling.