问题描述
对 WPF 相当陌生...
Fairly new to WPF...
我有一组要绑定到网格面板的数据.每个对象都包含其网格行和列,以及要在网格位置填写的内容.我真的很喜欢如何在列表框 XAML 中创建数据模板来创建一个 UI,而其背后的代码几乎没有任何内容.有没有办法为网格面板元素创建数据模板,并将面板绑定到数据集合?
I have a collection of data I would like to bind to a grid panel. Each object contains its grid row and column, as well as stuff to fill in at the grid location. I really like how I can create data templates in the listbox XAML to create a UI with almost nothing in the code behind for it. Is there a way to create a data template for grid panel elements, and bind the panel to a data collection?
推荐答案
您可以使用带有 Grid
作为其面板的 ItemsControl
.这是一个例子.XAML:
You can use an ItemsControl
with a Grid
as its panel. Here is an example. 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>
代码隐藏(用于测试目的):
Codebehind (for testing purposes):
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"}
};
}
这篇关于WPF 中有网格面板元素的数据模板吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!