我第一次尝试使用WPF,特别是使用ListView,我想将其绑定到代码后台页面上的ObservableCollection属性。现在我只是想了解事情是如何工作的,所以我试着保持简单。不幸的是,我不太清楚我在哪里出了问题。
我的代码后台页面有一个类似于这样的属性:
public ObservableCollection<Code> Code { get; set; }
我在表单上有一个按钮,用于查询并填充Code属性。
Code类是一个简单的POCO类:
public class Code
{
public string Line { get; set; }
}
我已经在XAML窗口中添加了一个命名空间:
<Window x:Class="SampleWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SampleWPF"
Title="MainWindow" Height="350" Width="525"
>
而ListView看起来像这样:
<DockPanel Height="311" HorizontalAlignment="Left" Name="dockPanel1"
VerticalAlignment="Top" Width="182">
<ListView Name="lstCode"
ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Window, AncestorLevel=1}, Path=Code}"
DisplayMemberPath="Line">
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding Line}" />
</GridView>
</ListView.View>
</ListView>
</DockPanel>
我也尝试在代码后台构造函数中设置DataContext,但没有成功,例如:
this.DataContext = this;
编辑:将这行代码移动到创建集合的代码之后,可以解决问题(以及其他建议的更改)。
我还尝试在代码中显式设置ItemsSource(在我的点击处理程序中):
this.lstCode.ItemsSource = this.Code;
我看了很多例子,但我还是有点不理解(这并不奇怪)。
注:本文为IT技术相关内容。