简体   繁体   中英

Main structure for a MVVM WPF

In one hand I have my model which had to collect data from several files and build a oriented object database, and in another I have my interface in which I want to display data from my database . So I use binding but my ComboBox, etc.. remain empty. I have the feeling that my database is built then erased when the interface is launched. Here's the code of my Main defined in the App.xaml.cs:

public partial class App : Application
{
    [STAThread]
    public static void Main()
    {
        var application = new App();
        application.InitializeComponent();
        DirectoryInfo dir = new DirectoryInfo("P:\\....");
        Model model = new Model(dir);
        model.entityBox.initialize();
        application.Run();
    }
}

Code for binding in MainWindow.xaml:

  <Window.DataContext>
    <local:EntityBox></local:EntityBox>
  </Window.DataContext>
  <Grid>
    <ComboBox x:Name="critereComboBox" ItemsSource="{Binding Criteres}"/>

In EntityBox.cs:

        private List<string> _criteres = new List<string>();
        public void initialize()
        {
            _criteres.Add("TXC");
            _criteres.Add("TYC");
            _criteres.Add("TZC");
            _criteres.Add("MXC");
            _criteres.Add("MYC");
            _criteres.Add("MZC");
        }
        public List<string> Criteres
        {
            get{ return _criteres; }
        }

You need to initialize combobox inside context class, because when you use XAML to bind your data context, the context class is created independently by XAML, the model creation in Main function has literally no effect to your Control. You also need to implement INotifyPropertyChanged to your Model (ViewModel?) class. I am also suggest you to step into MVVM approach.

I suppose it's a one-way binding. A short answer is to use ObservableCollection

private ObservableCollection<string> _criteres = new ObservableCollection<string>();

As it will notify when you call Add, but you might need to call them in UIDispatcher.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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