Сохранить Combobx Binding MVVM - PullRequest
       0

Сохранить Combobx Binding MVVM

0 голосов
/ 27 марта 2020

Я сделал комбобокс, в котором я добавил какое-то имя, но я хочу сохранить его, когда я снова открою приложение, чтобы получить имя, которое я добавил в прошлый раз, как я могу это сделать, вот код приложения.

Я пытался что-то с XmlSerializer, но он не работает.

Model.Parts:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;

namespace WpfApp1
{
    public class Parts : Changed
    {
        public string name;

        public string Name
        {
            get { return name; }
            set
            {
                if (name != value)
                {
                    name = value;
                    RaisePropertyChanged("Name");
                }
            }            
        }


    }
}

Model.Database:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.IO.Compression;
using System.IO;
using System.Xml.Serialization;

namespace WpfApp1
{
    public class DataBase
    {
        private static ObservableCollection<Parts> parts = new ObservableCollection<Parts>();
        public static string path_Xml_Files = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

        public ObservableCollection<Parts> Parts
        {
            get { return parts; }
            set
            {
                if(parts!=value)
                {
                    parts = value;
                }
            }
        }
        public ObservableCollection<Parts> ReadXmlCaseDimensions(string path)
        {
            XmlSerializer mySerializer = new XmlSerializer(typeof(ObservableCollection<Parts>));
            // To read the file, create a FileStream.  
            if (File.Exists(path))
            {
               // Parts.Clear();
                FileStream myFileStream = new FileStream(path, FileMode.Open);
                // Call the Deserialize method and cast to the object type.  
                Object o = (mySerializer.Deserialize(myFileStream));
                Parts = (ObservableCollection<Parts>)o;
                //CaseDimensions = (List<CaseDimension>)o;
                myFileStream.Close();
                return Parts;
            }
            return null;
        }

        public static void WriteXMLCaseDimensions(ObservableCollection<Parts> list)                                        //scriu casedimension in cazul dat de variabila index
        {
            System.Xml.Serialization.XmlSerializer writer = new System.Xml.Serialization.XmlSerializer(typeof(ObservableCollection<Parts>));
            var path = path_Xml_Files + "\\CMB"+ ".xml";
            System.IO.FileStream file = System.IO.File.Create(path);
            writer.Serialize(file, list);
            file.Close();
        }

    }
}

ViewModel :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Collections.ObjectModel;

namespace WpfApp1
{
    public class AddViewModel : Changed
    {

        private ObservableCollection<Parts> _persons;
        public string names;
        public AddViewModel()
        {
            Persons = new ObservableCollection<Parts>()
             {
                  new Parts{Name="Nirav"}
                 ,new Parts{Name="Kapil"}
                 ,new Parts{Name="Arvind"}
                 ,new Parts{Name="Rajan"}
             };

        }

public ObservableCollection<Parts> Persons
        {
            get { return _persons; }
            set {
                if (_persons != value)
                {
                    _persons = value;
                    RaisePropertyChanged("Persons");
                }
            }
        }
        private Parts _sperson;

        public Parts SPerson
        {
            get { return _sperson; }
            set {
                if (_sperson != value)
                {
                    _sperson = value;
                    RaisePropertyChanged("SPerson");
                }
            }
        }

    }
}

MainWindow:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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 WpfApp1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public AddViewModel addviewmodel;

        public MainWindow()
        {
            InitializeComponent();
            addviewmodel = new AddViewModel();
            DataContext = addviewmodel;
        }

        public AddViewModel getModel()
        {
            return addviewmodel;
        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
           // MessageBox.Show();
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {

                getModel().Persons.Add(new Parts { Name = cmbtxt.Text});
        }

    }
}

MainWindow.XAML

<Grid>
        <ComboBox ItemsSource="{Binding Persons}"   SelectionChanged="ComboBox_SelectionChanged" HorizontalAlignment="Left" Margin="391,17,0,0" VerticalAlignment="Top" Width="314" Height="27">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Path=Name}" />
                    </StackPanel>
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>
        <TextBox Name="cmbtxt" HorizontalAlignment="Left" Height="23" Margin="24,21,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="172" />
        <Button Content="Add" HorizontalAlignment="Left" Margin="24,88,0,0" VerticalAlignment="Top" Width="156" Height="49" Click="Button_Click"/>
    </Grid>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...