如何通过XAML绑定值

时间:2012-04-21 09:57:41

标签: .net wpf xaml data-binding

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

1 个答案:

答案 0 :(得分: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>

希望这会有所帮助