0

我将 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>
4

1 回答 1

0

你有两个选项来解决这个问题,第一个将 DataContext 设置为窗口或用户控件,第二个在绑定处使用元素名称。

这是第二个解决方案

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="WpfApplication6.MainWindow"
    x:Name="myWindow"
    Title="MainWindow"
    Width="640" Height="480">

  <Grid>
   <ListView Name="lstVw" ItemsSource="{Binding Path=Collection, ElementName=myWindow}" 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>

</Window>

希望这可以帮助

于 2012-04-21T10:31:35.893 回答