我是WPF / XAML的新手,在数据绑定和布局方面存在一些不错的问题。 我试图实现的目标: 一个带有一行网格单元格(仅Text和BackgroundColor)且在某些Textblock下方的列表。我的XAML看起来像这样:
<Window.Resources>
<DataTemplate x:Key="GridLayoutTemplate">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Rectangle Grid.Row="0" Grid.Column="0" Fill="{Binding RowData.RowColor}" />
<TextBlock Text="{Binding RowData.RowText}" />
</Grid>
</DataTemplate>
<DataTemplate x:Key="ListLayoutTemplate">
<StackPanel VerticalAlignment="Stretch">
<ItemsControl ItemTemplate="{StaticResource GridLayoutTemplate}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Rows="1" Columns="9"></UniformGrid>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
<Grid Background="Green">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Rectangle Grid.Row="0" Grid.Column="0" Fill="{Binding TileColor}" />
<TextBlock Grid.Row="0" Grid.Column="0" Text="{Binding TileText}" />
</Grid>
</StackPanel>
</DataTemplate>
</Window.Resources>
<ListView ItemTemplate="{StaticResource ListLayoutTemplate}" Name="lvDataBinding">
</ListView>
后面的代码:
public Test()
{
InitializeComponent();
List<DataObject> items = new List<DataObject>();
List<Row> rowItem = new List<Row>();
rowItem.Add(new Row()
{
RowColor = "Red",
RowText = "Text1"
});
rowItem.Add(new Row()
{
RowColor = "Blue",
RowText = "Text2"
});
items.Add(new DataObject()
{
TileColor = "Black",
TileText = "Blibb",
RowData = rowItem
});
items.Add(new DataObject() { TileColor = "Yellow", TileText = "Blubb", RowData=rowItem });
items.Add(new DataObject() { TileColor = "Red", TileText = "Blabb", RowData=rowItem });
this.lvDataBinding.ItemsSource = items;
}
}
public class DataObject
{
public string TileText { get; set; }
public string TileColor { get; set; }
public List<Row> RowData { get; set; }
}
public class Row
{
public string RowText { get; set; }
public string RowColor { get; set; }
}
如果我运行它,它将仅显示列表视图的行,而不显示统一网格。 列表视图项的绑定是可以的,但是我不知道统一网格,布局也可能是错误的。令人困惑。
答案 0 :(得分:1)
将ItemsSource
的{{1}}属性绑定到ItemsControl
,然后删除“ RowData”。从RowData
中的绑定路径开始:
GridLayoutTemplate