Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Update the view model in the xaml.cs file to add some logic in mvvm

I’m using mvvm for my application and I’m use binding to bind the items and change automaticly when there are some changes in my view but in some cases I want to add some logic and then send it to the view model. for example:

        private string _children;
        public string Children
        {
            get
            {
                return _children;
            }
            set
            {
                _children= value;
                OnPropertyChanged(nameof(Children));
            }

        }

And my view:

                <TextBox Name="Child"></TextBox>
                <Button Content="Add" Click="Add_Children"/>
                <ListView Name="ChildrenList">

                </ListView>
        private string children
        private void Add_Children(object sender, RoutedEventArgs e)
        {
            string name = Child.Text;
            ChildrenList.Items.Add(name);
            children += name;
        }

I want to send the children field to my view model, But I can’t because I don’t any access to the view model in xaml.cs file.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This example is not my exact problem. In this case I could just use a list instead of a string, But
I just wanted to ask a general question.

>Solution :

It’s not the best way to achieve this in MVVM, but you can access your ViewModel like this:

In your xaml.cs file:

Declare variable
YourViewModel vm;

Add this declaration to constructor
this.Loaded += new RoutedEventHandler(OnLoaded);

Create this method

public void OnLoaded(object sender, RoutedEventArgs e)
{
       vm = this.DataContext as TableDrawingsViewModel;
}

And then tou can access tour ViewModel instance by using this.vm

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading