【发布时间】:2014-10-19 06:20:11
【问题描述】:
对 WPF 相当陌生...
我有一组要绑定到网格面板的数据。每个对象都包含其网格行和列,以及要在网格位置填充的内容。我真的很喜欢如何在列表框 XAML 中创建数据模板来创建 UI,而其背后的代码几乎没有任何内容。有没有办法为网格面板元素创建数据模板,并将面板绑定到数据集合?
【问题讨论】:
标签: c# wpf grid datatemplate
对 WPF 相当陌生...
我有一组要绑定到网格面板的数据。每个对象都包含其网格行和列,以及要在网格位置填充的内容。我真的很喜欢如何在列表框 XAML 中创建数据模板来创建 UI,而其背后的代码几乎没有任何内容。有没有办法为网格面板元素创建数据模板,并将面板绑定到数据集合?
【问题讨论】:
标签: c# wpf grid datatemplate
您可以使用ItemsControl 和Grid 作为其面板。这是一个例子。 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"}
};
}
【讨论】:
不确定这是否对您有所帮助,但您为什么不尝试将 ItemsControl(ListBox、ListView)的 ItemsPanel 设置为 UniformGrid。像这样的:
<ItemsControl>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
它与之前的解决方案类似,只是动态化了一点。
【讨论】: