ObservableCollection没有更新

时间:2015-12-16 17:56:59

标签: c# wpf windows xaml

我的ObservableCollection有问题,我不知道怎么做。 我与我的SQl基础连接(使用EF)。

 public class ProductModel 

{
    private static List<ProductDbObject> ProductDbObjects { get; set; }
    public ObservableCollection<ProductDbObject> OProductDbObjects { get; set; }

    public ProductModel()
    {
        CollectionChanged();

    }
    public void CollectionChanged()
    {
        ProductDbObjects = new List<ProductDbObject>();
        ProductDbObjects = Services.productService.GetAll();
        OProductDbObjects = new ObservableCollection<ProductDbObject>(ProductDbObjects);
    }
}

}

我从base获取所有项目并将其保存在ObservableCollection的列表和列表中。

<Window x:Class="NoweChili.View.AdminView.EditProductView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:NoweChili.View.AdminView"
    mc:Ignorable="d"
    Title="Edycja Produktów" Height="600" Width="800">

<Grid Margin="20" >
    <Grid.RowDefinitions>
        <RowDefinition Height="5*"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
     <ColumnDefinition Width="5*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <ListView x:Name ="ProductListListView"  ItemsSource="{Binding OProductDbObjects}" ></ListView>
    <Grid Grid.Row="0" Grid.Column="1">
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="0.1*"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="0.3*"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="5*"/>
        </Grid.RowDefinitions>
        <Button x:Name="ProductEditButton" Click="ProductEditButton_OnClick" Content="Edytuj"></Button>
        <Button x:Name="ProductDeleteButton" Click="ProductDeleteButton_OnClick" Content="Usuń" Grid.Row="2"></Button>
        <Button x:Name="ProductBackButton"  Content="Cofnij" Grid.Row="4"></Button>
    </Grid>

</Grid>

项目显示正确,但当我删除其中一个时,observableCollection没有更新,项目仍在列表中。

 private void ProductDeleteButton_OnClick(object sender, RoutedEventArgs e)
    {
       ProductDbObject productToDelete = new ProductDbObject();
        productToDelete = (ProductDbObject) ProductListListView.SelectedItem;
        if (productToDelete == null)
        {
            var result = MessageBox.Show("Proszę zaznaczyć obiekt na liście");
        }

        else
        {
            Services.productService.DeleteEntity(productToDelete);
            Services.productService.SaveChange();            
        }
你帮我吗? :)

1 个答案:

答案 0 :(得分:0)

我认为问题在于,尽管您已使用该服务删除产品,但这并未从ObservableCollection中删除产品 - 您需要调用Remove(productToDelete)