Share via

How I can call a Init() function from my ViewModel?

Markus Freitag 3,791 Reputation points
2020-07-14T10:13:10.147+00:00

Hello, How I can call a Init() function from my ViewModel?

<Grid DataContext="{StaticResource vm}">
What is different with StaticResource and without?

I need without static, then the list works not.12142-image-01.png

12143-image-02.png

public partial class MainWindow : Window  
    {  
        public MainWindow()  
        {  
            InitializeComponent();  
  
  
            //DataContext.  
            ((ViewModel)DataContext).Init();  
        }     
     
    }  

Not possible, why?

Developer technologies | Windows Presentation Foundation

Answer accepted by question author

Peter Fleischer (former MVP) 19,351 Reputation points
2020-07-18T06:02:37.607+00:00

There are various ways to call a method from the code-behind.

  1. approach:
    public partial class MainWindow : Window
    {
      public MainWindow()
      {
        ViewModel vm = new ViewModel();
        this.DataContext = vm;
        InitializeComponent();
        vm.Init();
      }
    }
    
  2. approach:
    public MainWindow()
    {
      this.Resources.Add("vm", new ViewModel());
      this.Loaded += MainWindow_Loaded;
      InitializeComponent();
    }
    
    private void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
      var vm = (ViewModel)(this.Resources["vm"]);
      vm.Init();
    }
    

Was this answer helpful?

1 person found this answer helpful.
0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.