WPF列表框绑定更新 [英] WPF ListBox Binding Update

查看:157
本文介绍了WPF列表框绑定更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的品牌新的WPF,我只是设法绑定特定类项目的列表框的列表。列表框现在已经成功地显示它们。下面是一些code,类第一:

I'm brand new to WPF and I just managed to bind a list of specific class items to a ListBox. The ListBox now successfully displays them. Here's some code, the class first:

public class OrderItem
{
    public int Quantity { get; set; }
    public string Name { get; set; }
    public Double Price { get; set; }
}

某些伪数据和结合,这一切都发生在主程序的构造

Some dummy data and the binding, which all happens in the constructor of the main program:

List<OrderItem> currentOrderItems = new List<OrderItem>();
        currentOrderItems.Add(new OrderItem() { Quantity = 5, Name = "Test", Price = 5 });
        currentOrderItems.Add(new OrderItem() { Quantity = 15, Name = "Test test", Price = 6.66 });
        currentOrderItems.Add(new OrderItem() { Quantity = 1, Name = "Test 3", Price = 15.88 });
        listOrderItems.ItemsSource = currentOrderItems;

和XAML中:

<ListBox HorizontalAlignment="Left" Margin="150,27,0,23" Name="listOrderItems" Width="150" FontFamily="Times New Roman" FontSize="12">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid Margin="4">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto" />
                        <ColumnDefinition Width="Auto" />
                        <ColumnDefinition Width="Auto" />
                    </Grid.ColumnDefinitions>
                    <TextBlock Text="{Binding Quantity}" FontWeight="Bold"  />
                    <TextBlock Grid.Column="1" Text="{Binding Name }" />
                    <TextBlock Grid.Column="2" Text="{Binding Price }" />
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

我的问题是我怎么可以更新列表框,以显示我加入到含有又名的的OrderItems的数据列表中的新项目。如果我添加,删除或修改以任何方式列表,这并没有反映在ListBox中。
谢谢!

My question is how can I update the ListBox to display a new item that I'm adding to the List containing the data a.k.a. the OrderItems. If I add, remove or modify the List in any way, this is not reflected in the ListBox. Thanks!

推荐答案

有关你的情况最好的方式使用MVVM百通。
简单来说:
您的模型OrderItem的应该实现接口的 INotifyPropertyChanged的
如果属性的改变,但收到通知。
然后创建视图模型,并设置它的DataContext。在视图模型添加的ObservableCollection 用的OrderItems,此集合应通知有关它的变化视图。
更多信息,请阅读一些这样的文章: MVVM

For your case best way use mvvm patern. In brief: Your model OrderItem should implement interface INotifyPropertyChanged. If property changed, it notified about this. Then create viewmodel and set it in datacontext. In viewModel add ObservableCollection with OrderItems, this collection should notified view about changes in it. for more information read some articles like this: MVVM

这篇关于WPF列表框绑定更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆