小编Pau*_*aul的帖子

无法将WPF ListView绑定到ObservableCollection

我第一次使用WPF,特别是使用我想绑定到ObservableCollection的ListView,后者是代码隐藏页面上的属性.现在我只是想了解事情是如何运作的,所以我试着保持这个简单.不幸的是,我不太清楚我在哪里出错了.

我的代码隐藏页面有一个如下所示的属性:

public ObservableCollection<Code> Code { get; set; }
Run Code Online (Sandbox Code Playgroud)

我在表单上有一个按钮,用于查询和填充Code属性.

Code类是一个简单的POCO类:

public class Code
{
   public string Line { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我在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"                
        >
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

我还尝试在构造函数后面的代码中设置DataContext,没有运气,例如:

this.DataContext = this;
Run Code Online (Sandbox Code Playgroud)

编辑:将此行移至创建集合的代码行后固定的东西(以及建议的其他更改).

我还尝试在代码中显式设置ItemsSource(在我的点击处理程序中):

this.lstCode.ItemsSource = this.Code;
Run Code Online (Sandbox Code Playgroud)

我看了很多例子,但我在这里仍然遗漏了一些东西(并不是真的很惊讶).

wpf

6
推荐指数
1
解决办法
2万
查看次数

标签 统计

wpf ×1