bind in code behind

Feb 19, 2012 at 4:38 PM

Hi. I have a project that uses the galasoft mvvm light toolkit. I have a problem.

I need to catch changes to a property in my viewmodel from my codebehind. I already did bind in my xaml and that works fine. However I need to do other things from the codebehind when the propery in the viewmodel changes. Im using the observableobject. Could someone provide an example how to catch those events in the View codebehind plz? I assume its quite simple, however Googling has brought me nowhere :-)

Coordinator
Feb 19, 2012 at 5:01 PM

Hi,

This is very simple. Get a reference to your VM in the code behind:

public MyViewModel Vm
{
    get
    {
        return (MyViewModel)DataContext;
    }

then, in the Page's constructor, after the call to InitializeComponent, add an event handler to Vm.PropertyChanged.

Hope this helps,

Laurent

Feb 19, 2012 at 5:51 PM

Thx. I follow you all the way to the eventhandler. Could you show me in example.

If this is my viewModel object

 

public string

WelcomeTitle

{

 

get

{

 

return

_welcomeTitle;

}

 

set

{

 

if (_welcomeTitle == value

)

{

 

return

;

}

_welcomeTitle =

value

;

RaisePropertyChanged(WelcomeTitlePropertyName);

}

}

 

How do attach that as an eventhandler in my View?

Coordinator
Feb 20, 2012 at 8:04 PM

 

namespace MvvmLight4
{
    public partial class MainPage : UserControl
    {
        public MainViewModel Vm
        {
            get
            {
                return (MainViewModel)DataContext;
            }
        }

        public MainPage()
        {
            InitializeComponent();

            Vm.PropertyChanged += (s, e) =>
            {
                if (e.PropertyName == MainViewModel.WelcomeTitlePropertyName)
                {
                    // Do something
                }
            };
        }
    }
}