对 WPF 相当陌生......
我有一组数据要绑定(bind)到网格面板。每个对象都包含其网格行和列,以及要在网格位置填充的内容。我真的很喜欢我如何在列表框 XAML 中创建数据模板来创建一个 UI,而其背后的代码几乎没有任何内容。有没有办法为网格面板元素创建数据模板,并将面板绑定(bind)到数据集合?
最佳答案
您可以使用带有 Grid
的 ItemsControl
作为其面板。这是一个例子。 XAML:
<ItemsControl x:Name="myItems">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
</Grid>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding MyText}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemContainerStyle>
<Style>
<Style.Setters>
<Setter Property="Grid.Row" Value="{Binding MyRow}" />
<Setter Property="Grid.Column" Value="{Binding MyColumn}" />
</Style.Setters>
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
代码隐藏(用于测试目的):
public Window1()
{
InitializeComponent();
myItems.ItemsSource = new[] {
new {MyRow = 0, MyColumn = 0, MyText="top left"},
new {MyRow = 1, MyColumn = 1, MyText="middle"},
new {MyRow = 2, MyColumn = 2, MyText="bottom right"}
};
}
关于c# - WPF 中是否有用于网格面板元素的数据模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3251081/