我在将数据绑定到 Grid 时遇到问题,生成了元素但不在正确的行和列中
那时分配源时,所有数据都将存在,但不在正确网格的行和列中,所有控件将在第 0 列和第 0 行中呈现
我的代码低于 Xaml
<UserControl.Resources>
<DataTemplate x:Name="DTItemTemp">
<Border Width="200" Height="Auto" BorderBrush="Red" BorderThickness="2" Grid.Row="{Binding Grow}" Grid.Column="{Binding Gcol}" Margin="5">
<StackPanel Orientation="Vertical" >
<TextBlock Text="{Binding Name, Mode=OneWay}"></TextBlock>
<TextBlock Text="{Binding Grow, Mode=OneWay, StringFormat='Row {0}'}"></TextBlock>
<TextBlock Text="{Binding Gcol, Mode=OneWay, StringFormat='Col {0}'}"></TextBlock>
</StackPanel>
</Border>
</DataTemplate>
<DataTemplate x:Name="DTGridTemp">
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Name, Mode=OneWay}"></TextBlock>
<Grid ShowGridLines="True" Margin="10">
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<ItemsControl ItemsSource="{Binding MyItem,Mode=TwoWay}"
ItemTemplate="{StaticResource DTItemTemp}"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" />
</Grid>
</StackPanel>
</DataTemplate>
<DataTemplate x:Name="DTStack">
</DataTemplate>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White">
<ItemsControl x:Name="stksource" ItemTemplate="{StaticResource DTGridTemp}"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" />
</Grid>
Cs 文件
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
mydata data = new mydata();
data.DTGrid = new List<Grids>();
for (int i = 0; i < 3; i++)
{
Grids grd = new Grids();
grd.MyItem = new List<Items>();
grd.Name = string.Format("Grid of {0}", i);
for (int j = 0; j < 3; j++)
{
Items it = new Items();
it.Name = string.Format("Item {0} of {1}", i, j);
it.Grow = 0;
it.Gcol = j;
grd.MyItem.Add(it);
}
data.DTGrid.Add(grd);
}
stksource.ItemsSource = data.DTGrid;
}
}
public class mydata
{
public List<Grids> DTGrid { get; set; }
}
public class Grids
{
public string Name { get; set; }
public List<Items> MyItem { get; set; }
}
public class Items
{
public string Name { get; set; }
public int Grow { get; set; }
public int Gcol { get; set; }
}