ObservableCollection不反映UI

时间:2014-08-18 03:59:44

标签: c# wpf mvvm

我是WPF和MVVM的初学者。在对其进行编码时,我遇到了VehicleAddViewModel类中的ListItems变量的问题,该类的类型为ObservableCollection List。 从View到ViewModel的绑定是正确的,ListItems正在更新,Even OnPropertyChanged方法也在工作,但是当我向ListItems添加新的List时,它没有反映到UI。

另一方面,如果我将ListItems对象设为静态,它就会开始工作。 我不知道为什么会这样。

我很想知道为什么会这样。

我有大量文件,所以只为我的工作和非工作版本提供相关文件,如果您需要任何其他文件,请告诉我。

ListOfVehicle.xaml

<Window x:Class="Seris.ListOfVehicle"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="ListOfVehcle" Height="600" Width="700"
            xmlns:l="clr-namespace:Seris.ViewModels"
            xmlns:cnv="clr-namespace:Seris.Converters">
<Window.Resources>
    <cnv:ID2Name x:Key="converter" />
</Window.Resources>

<Grid HorizontalAlignment="Center">

    <Label Content="Manage Vehicle" HorizontalAlignment="Left" Height="27" Margin="261,8,0,0" VerticalAlignment="Top" Width="103" FontWeight="Bold" FontSize="12"/>
    <Label Content="SERIS CAD" HorizontalAlignment="Left" Height="30" Margin="53,8,0,0" VerticalAlignment="Top" Width="84" FontWeight="Bold"/>
    <Menu x:Name="ListOfPersonnnel" HorizontalAlignment="Left" Height="32" Margin="10,35,0,0" VerticalAlignment="Top" Width="603">
        <MenuItem Header="Manage Vehicle &gt;&gt;" />
    </Menu>

    <Button Name="Add_Button" CommandParameter="add"  Command="{Binding OpenAddWindow_Command}"  Content="Add" Height="28" Width="81" Margin="246,396,315,46"/>
    <Button Name="Replace_Button" CommandParameter="replace" Command="{Binding ReplaceButton_Command}" IsEnabled="{Binding IsEnableReplaceButton, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"  Content="Replace" Height="28" Width="81" Margin="345,396,216,46"/>
    <Button Name="Remove_Button" CommandParameter="remove" Command="{Binding RemoveButton_Command}" IsEnabled="{Binding IsEnableReplaceButton, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"  Content="Remove" Height="28" Width="81" Margin="442,396,119,46"/>


    <ListView Name ="Grid" Margin="104,67,185,226" >
        <DataGrid Name="DG" ItemsSource="{Binding ListItems, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding SelectedRow, Mode=TwoWay}"  SelectionMode="Single" GridLinesVisibility="None" IsReadOnly="True" AutoGenerateColumns="False" BorderThickness="0">
            <DataGrid.DataContext>
                <l:VehicleAddViewModel />
            </DataGrid.DataContext>
            <DataGrid.Columns>
                <DataGridTextColumn Header="Vehicle No" Binding="{Binding VehicleNo}"/>
                <DataGridTextColumn Header="Model" Binding="{Binding Model}" />
                <DataGridTextColumn Header="ManufacturingDate" Binding="{Binding ManufacturingDate}" />
                <DataGridTextColumn Header="IUNo" Binding="{Binding IUNo}" />
                <DataGridTextColumn Header="Personnel" Binding="{Binding PersonnelNameSelected, Converter={StaticResource converter} }" />
                <DataGridTextColumn Header="Unique No" Binding="{Binding UniqueNo}"/>
            </DataGrid.Columns>
        </DataGrid>
    </ListView>
    <TextBox Name="Search_Text" Text="{Binding SearchString, Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Height="23" Margin="520,72,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" />


</Grid>

</Window>

ListOfVehicle.xaml.cs

using Seris.ViewModels;
using Seris.Views;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Seris
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class ListOfVehicle : Window
{
    public ListOfVehicle()
    {
        this.DataContext = VehicleMainViewModel.getInstance;
        this.Show();
        InitializeComponent();
    }


}
}

ObservableObject.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows;

namespace Seris.Models
{
public abstract class ObservableObject: INotifyPropertyChanged, IDisposable
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected bool OnPropertyChanged(string propertyName)
    {

        this.VerifyPropertyName(propertyName); 

        PropertyChangedEventHandler handler = PropertyChanged;

        if(handler!=null)
        {
            if (propertyName != null)
            {

                handler(this, new PropertyChangedEventArgs(propertyName));
                return true;

            }
        }
        return false;
    }

    public void VerifyPropertyName(string propertyName)
    {
        if (TypeDescriptor.GetProperties(this)[propertyName] == null)
        {
            string msg = "Invalid Property Name: " + propertyName;

            if (this.ThrowOnInvalidPropertyName)
                throw new Exception(msg);
            else
                Debug.Fail(msg);
        }
    }

    public virtual void Dispose()
    {
        // To Override this method
    }

    public bool ThrowOnInvalidPropertyName { get; set; }
}
}

VehicleAddViewModel.cs

...

    private ObservableCollection<VehicleModel> _listItems =  new ObservableCollection<VehicleModel>();
    public ObservableCollection<VehicleModel> ListItems
    {
        get { return _listItems; }
        set
        {
            if (value == null || (!value.Equals(_listItems)))
            {
                _listItems = value;
                OnPropertyChanged("ListItems");
            }
        }
    }
    ...


    public void SaveToList(object o1)
    {

        try
        {
            // Setting Flags
            ErrorMessage = "";

            //Checking a duplicate entry

            if (isDuplicate())
            {
                throw (new Exception("Duplicate Entries are not allowed"));
            }


            // Adding a Record

            using(vm = new VehicleModel(true,VehicleNo, Model, ManufacturingDate, IUNo, PersonnelNameSelected))
            {


                // Keeping record of selected Row

                int indexToRemove;

                if (SelectedRow != null && ReplaceFlag==true) 
                {
                    ReplaceFlag = false;

                    VehicleModel selectedRecord = ListItems.First(x => x.UniqueNo == UniqueNo);
                    indexToRemove = ListItems.IndexOf(selectedRecord);

                    ListItems.Insert(indexToRemove, new VehicleModel(vm));

                    ListItems.RemoveAt(indexToRemove + 1);
                }
                else
                    ListItems.Add(new VehicleModel(vm));



            }
            VehicleMainViewModel.getInstance.CloseAdd();

            // Clearing Form

            clearAllData();

        }
        catch (Exception ex)
        {
            ErrorMessage = ex.Message;
        }
    }

   ...

    public VehicleAddViewModel()
    {
         // Setting Flags
        ErrorMessage = "";
        IsEnableReplaceButton = false;

        // Commands Initialization
        try
        {
            SaveButton_Command = new RelayCommand(new Action<object>(SaveToList));

        }
        catch(Exception ex)
        {
            showMessage("Exception Occured in Command Variables");
        }

    } 

    #endregion


}
}

VehicleMainViewModel

{
public class VehicleMainViewModel: ObservableObject
{


    ...

    public VehicleMainViewModel()
    {
        //VehicleMainViewModel.ListItems = new ObservableCollection<VehicleModel>();
        //VehicleMainViewModel.PersonnelObject = PersonnelMainViewModel.getInstance._Personnel_List;

        try
        {
            ReplaceButton_Command = new RelayCommand(new Action<object>(ReplaceToList));
            RemoveButton_Command = new RelayCommand(new Action<object>(RemoveList));
            OpenAddWindow_Command = new RelayCommand(new Action<object>(OpenAdd));
        }
        catch (Exception ex)
        {
            VehicleAddViewModel.showMessage("Exception Occured in Command Variables");
        }
    }
}
}

&#34;现在我只更改了2个文件VehicleAddViewModel和VehicleMainViewModel,如下所示,我所做的只是使ListView对象静态,它开始工作......&#34; < / p>

VehicleAddViewModel

public class VehicleAddViewModel : ObservableObject
{
 . . .
    private static ObservableCollection<VehicleModel> _listItems = new ObservableCollection<VehicleModel>();
    public static ObservableCollection<VehicleModel> ListItems
    {
        get { return _listItems; }
        set
        {
            if (value == null || (!value.Equals(_listItems)))
            {
                _listItems = value;
            }
        }
    }

    #region Methods

    private VehicleModel vm;


    public void SaveToList(object o1)
    {

        try
        {
            // Setting Flags
            ErrorMessage = "";

            //Checking a duplicate entry

            if (isDuplicate())
            {
                throw (new Exception("Duplicate Entries are not allowed"));
            }


            // Adding a Record

            using(vm = new VehicleModel(true,VehicleNo, Model, ManufacturingDate, IUNo, PersonnelNameSelected))
            {


                // Keeping record of selected Row

                int indexToRemove;

                if (SelectedRow != null && ReplaceFlag==true) 
                {
                    ReplaceFlag = false;

                    VehicleModel selectedRecord = ListItems.First(x => x.UniqueNo == UniqueNo);
                    indexToRemove = ListItems.IndexOf(selectedRecord);

                    ListItems.Insert(indexToRemove, new VehicleModel(vm));

                    ListItems.RemoveAt(indexToRemove + 1);
                }
                else
                    ListItems.Add(new VehicleModel(vm));



            }
            VehicleMainViewModel.getInstance.CloseAdd();

            // Clearing Form

            clearAllData();

        }
        catch (Exception ex)
        {
            ErrorMessage = ex.Message;
        }
    }


    public VehicleAddViewModel()
    {

        // Setting Flags
        ErrorMessage = "";
        IsEnableReplaceButton = false;

        // Commands Initialization
        try
        {
            SaveButton_Command = new RelayCommand(new Action<object>(SaveToList));

        }
        catch(Exception ex)
        {
            showMessage("Exception Occured in Command Variables");
        }

    } 

    #endregion


}
}

0 个答案:

没有答案