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

Time:01-20

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.

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.

CodePudding user response:

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 onl oaded(object sender, RoutedEventArgs e)
{
       vm = this.DataContext as TableDrawingsViewModel;
}

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

  • Related