很难将列表绑定到datagrid:
XAML:
<DataGrid Name="dgProductList"
ItemsSource="{Binding ProductList}">
<DataGridTextColumn Binding="{Binding ProductName}" Header="Item" />
<DataGridTextColumn Binding="{Binding Quantity}" Header="Qty" />
<DataGridTextColumn Binding="{Binding TotalPrice}" Header="Price" />
<DataGridTemplateColumn Width="*">
代码背后:
public IList<SalesItem> ProductList = new List<SalesItem>();
public void LoadProduct(Product product)
{
SalesItem item = new SalesItem { ProductName = product.Name, Quantity = 1, TotalPrice = product.Price };
ProductList.Add(item);
}
它无法加载。
谢谢。
答案 0 :(得分:1)
尝试将您的收藏绑定到
ObservableCollection<SalesItem>
添加产品时可能不会通知用户界面。
答案 1 :(得分:1)
dataGrid不会知道ProductList何时更新...像这样制作一个ObservableCollection:
public ObservableCollection<SalesItem> ProductList = new ObservableCollection<SalesItem>();
修改强>
绑定是否正常工作?将控件/窗口命名为Root并绑定到该元素
<Window x:Class="test.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" x:Name="Root">
<Grid>
<DataGrid Name="dgProductList" ItemsSource="{Binding ElementName=Root,Path=ProductList}">
<DataGridTextColumn Binding="{Binding ProductName}" Header="Item" />
<DataGridTextColumn Binding="{Binding Quantity}" Header="Qty" />
<DataGridTextColumn Binding="{Binding TotalPrice}" Header="Price" />
</DataGrid>
</Grid>
</Window>