【发布时间】:2012-04-21 09:57:41
【问题描述】:
我正在将 DataTable 值绑定到 ObservableCollection 并尝试将项目绑定到 ListView。
当我通过 XAML 进行绑定时,例如:ItemsSource="{Binding Collection}",它不会显示值,但是当我使用 C# 代码绑定值时,它会正确显示它们。
我找不到这种行为的原因。请提出解决方案...
在 C# 代码中:
// Declaration of the Observable Collection item.
ObservableCollection<DataTable> _observableCollection = new ObservableCollection<DataTable>();
public ObservableCollection<DataTable> Collection
{
get { return _observableCollection; }
}
通过 C# 代码绑定数据:
lstVw.ItemsSource = Collection;
在 XAML 中:
<Grid>
<ListView Name="lstVw" ItemsSource="{Binding Path=Collection}" Height="auto" Width="Auto" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<ListView.View>
<GridView>
<GridViewColumn Header="OrderID" Width="auto" >
<GridViewColumn.CellTemplate>
<DataTemplate>
<Button Tag="{Binding OrderID}" Content="{Binding OrderID}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Width="auto" DisplayMemberBinding="{Binding CustomerID}" Header="CustomerID" />
<GridViewColumn Width="auto" DisplayMemberBinding="{Binding ProductID}" Header="ProductID" />
</GridView>
</ListView.View>
</ListView>
</Grid>
【问题讨论】:
-
可能 DataContext 不正确。您在哪里/如何设置窗口或控件的数据上下文?
-
实际上我没有得到你的话,先生。在这里我使用 itemmsSource 选项而不是 DataContext
-
您的集合在代码隐藏中,但您必须为 XAML 设置数据上下文,例如在代码中:RootGrid.DataContext = this;
标签: .net wpf xaml data-binding