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

Markus Freitag 3,786 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?

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,691 questions
{count} votes

Accepted answer
  1. Peter Fleischer (former MVP) 19,306 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();
      }
      
    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful