数据网格的XAML绑定
本文关键字:XAML 绑定 网格 数据网 数据 | 更新日期: 2023-09-27 17:51:13
这里是DataGrid的XAML绑定需求。
- 我有4个列表(
IList<T>
)在我的代码文件 - 需要使用4列WPF DataGrid; 每列1列
- 需要将每个列表绑定到网格中相应的列
- 您可以假设在网格的列上显示每个列表中的字符串
我的问题是如何在DataGridcolumnTemplate中使用这些列表(例如,ListBox等)有人能解释一下吗?
如果要绑定到Data网格,最好使用List,而不是单独的List。
例如,你有一个Class:
public class Product
{
public decimal guProductId { get; set; }
public string productCode { get; set; }
}
List<Product> Products;
可以绑定到一个数据网格,而不是像下面那样有单独的GuProductID和ProductCodes列表。
List<decimal> guProductIds;
List<string> productCodes;
将List绑定到datagrid而不是单独的List是很容易的。
WPF DataGrid派生自ItemsControl,这意味着它只支持绑定到一个集合。这是我的理解。所以我认为在你的情况下,一个可能的解决方案是使用四个列表框控件并排对齐,并制作样式,使它们看起来更像一个网格,如果你想要类似的外观和感觉。
如果你没有义务使用DataGrid,为什么不创建你自己的usercontrol来承载4个listbox,并用每个List填充它们呢?像这样…
<UserControl x:Class="Listboxes.ListBoxes"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
<DataTemplate x:Key="lbItemTemplate">
<Label Content="{Binding}"/>
</DataTemplate>
</UserControl.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<ListBox Grid.Column="0"
ItemsSource="{Binding}"
ItemTemplate="{StaticResource lbItemTemplate}"/>
<ListBox Grid.Column="1"
ItemTemplate="{StaticResource lbItemTemplate}"/>
<ListBox Grid.Column="2"
ItemTemplate="{StaticResource lbItemTemplate}"/>
<ListBox Grid.Column="3"
ItemTemplate="{StaticResource lbItemTemplate}"/>
</Grid>
</UserControl>