我正在尝试在WinRT中构建一个DataGrid。当我开始这个时,DataGrid有它的全尺寸。 但是当我用WinRTXamlToolkit.Debugging工具检查时,我看到我的_itemsPanel的渲染大小为0。 我认为找到问题的最简单方法是将整个代码粘贴到此处^^
<local:DataGrid ItemsSource="{Binding Material}">
<local:DataGrid.ItemTemplate>
<DataTemplate>
<Grid Background="White">
<TextBlock Text="{Binding Name}" Margin="5" />
</Grid>
</DataTemplate>
</local:DataGrid.ItemTemplate>
</local:DataGrid>
这是我的DataGrid类:
public class DataGrid : Panel
{
private StackPanel _itemsPanel;
public DataTemplate ItemTemplate { get; set; }
public static readonly DependencyProperty ItemsSourceProperty =
DependencyProperty.Register("ItemsSource",
typeof(IEnumerable<Object>),
typeof(DataGrid),
new PropertyMetadata(0, ItemsSourceChangedCallback));
private static void ItemsSourceChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs args)
{
if (args.NewValue == null)
return;
if (args.NewValue == args.OldValue)
return;
DataGrid dataGrid = d as DataGrid;
if (dataGrid == null)
return;
var obsList = args.NewValue as INotifyCollectionChanged;
if (obsList != null)
{
dataGrid.Render();
}
}
public IEnumerable<Object> ItemsSource
{
get { return (IEnumerable<Object>)GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
public DataGrid()
{
_itemsPanel = new StackPanel();
_itemsPanel.Height = 800;
_itemsPanel.Width = 400;
_itemsPanel.Margin = new Thickness(10, 10, 10, 10);
_itemsPanel.Background = new SolidColorBrush(Colors.White);
Children.Add(_itemsPanel);
}
public void Render()
{
_itemsPanel.Children.Clear();
foreach (object item in ItemsSource)
{
FrameworkElement element = ItemTemplate.LoadContent() as FrameworkElement;
if (element == null)
return;
element.DataContext = item;
_itemsPanel.Children.Add(element);
}
}
protected override Size ArrangeOverride(Size finalSize)
{
return base.ArrangeOverride(finalSize);
}
protected override Size MeasureOverride(Size availableSize)
{
this.Clip = new RectangleGeometry { Rect = new Rect(0, 0, availableSize.Width, availableSize.Height) };
foreach (FrameworkElement container in Children)
{
container.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
}
return availableSize;
}
}
希望你能帮助我:)。