简体   繁体   English

WPF ListView与ObservableCollection的绑定问题

[英]WPF ListView Binding issues with ObservableCollection

I have a ListView which binds to an ObservableCollection named GunsCollection 我有一个ListView绑定到名为GunsCollectionObservableCollection

<Grid>
<ListView x:Name="lstView" Height="300" ItemsSource="{Binding GunsCollection}">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Gun Name" Width="120" DisplayMemberBinding="{Binding ModelName}"/>
            <GridViewColumn Header="Price" Width="120" DisplayMemberBinding="{Binding UnitCost}"/>
        </GridView>
    </ListView.View>
</ListView>

When I create the instance of GunsCollection in the constructor of MainWindow , my ListView doesn't show anything and is empty. 当我在MainWindow的构造函数中创建GunsCollection实例时,我的ListView不显示任何内容,并且为空。

public partial class MainWindow : Window
{
    public ObservableCollection<Gun> GunsCollection { get; set; } 
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;
        var GunsCollection = new ObservableCollection<Gun>() // doesn't work!
        {
            new Gun() {ModelName = "AK-47", UnitCost = 2700 },
            new Gun() {ModelName = "M4A4", UnitCost = 3100 },
        };
    }
}

But when I create the instance of GunsCollection on the same line with its declaration, the ListView works and shows all of the items contained. 但是,当我在其声明的同一行上创建GunsCollection实例时, ListView可以工作并显示其中包含的所有项目。

public partial class MainWindow : Window
{
    public ObservableCollection<Gun> GunsCollection { get; set; } = new ObservableCollection<Gun>(); 
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;
        GunsCollection.Add(new Gun() { ModelName = "AK-47", UnitCost = 2700 });
        GunsCollection.Add(new Gun() { ModelName = "M4A4", UnitCost = 3100 });
    }
}

Why is this happening? 为什么会这样呢?

In your first example the GunsCollection you fill with data will no longer exist after the constructor has been executed. 在您的第一个示例中,在构造函数执行后,用数据填充的GunsCollection将不再存在。 You've created a new variable which has nothing to do with your class property (even if it has the same name). 您已经创建了一个新变量,该变量与您的class属性无关(即使它具有相同的名称)。

The first example you display, you create a new local variable and don't assign it to your public collection which is bound to your view. 显示的第一个示例创建了一个新的局部变量,并且未将其分配给绑定到视图的公共集合。

public partial class MainWindow : Window
{
    public ObservableCollection<Gun> GunsCollection { get; set; } 
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;
        GunsCollection = new ObservableCollection<Gun>() 
        {
            new Gun() {ModelName = "AK-47", UnitCost = 2700 },
            new Gun() {ModelName = "M4A4", UnitCost = 3100 },
        };
    }
}

Remove var 删除var

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM