-1

While doing WPF with MVVM structure, I always bind my View to ViewModel using Getter-Setter on variables of class. Isn't there anyway such that I can bind to directly Methods of ViewModel?

( Please make sure that as I am using MVVM, I don't expect code behind of view such that method(sender s,...) )

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
Pratik
  • 161
  • 4
  • 13

3 Answers3

1

You are looking for Commands in WPF. Which is simply a command patter, which allows you to turn "method" into an object and thus be able to bind it as normal variable.

On the other hand, if you want to "bind to method" just to display it's data, then creating a property is extremely simple. I don't see a problem with this approach.

Euphoric
  • 12,645
  • 1
  • 30
  • 44
  • You are right but Commands are limited to components like Buttons only. – Pratik Aug 06 '14 at 05:11
  • @Pratik Would you please specify more what do you want to bind to what? What is your exact problem? – Euphoric Aug 06 '14 at 05:13
  • I want to bind with LostFocus event of TextBox. Its for the validation purpose of content of TextBox. – Pratik Aug 06 '14 at 05:15
  • @Pratik naturally you don't have to bind methode because you have already bound value (of your textbox) to prop. So you can call methode from props setter. in your case with lostfocus maybe try somthing – Den Aug 06 '14 at 05:29
  • 1
    @Pratik Bind the text to a property and set the bindings to update on `LostFocus`. Using the `LostFocus` event is completely unnecessary. – jamesSampica Aug 06 '14 at 05:30
  • I have already UpdateSourceTrigger=OnChangeProperty to TextBox, so I have data saved in ViewModel already, Can I just know whether is it possible to bind directly to method in ViewModel or not? – Pratik Aug 06 '14 at 05:39
0

I don't understand your requirements clearly, but Why don't you create a property and call that method on the get property

Thakur
  • 559
  • 6
  • 15
0

you can acheive this using interaction triggers which allows you to bind any event to the methods in the viewmodel. Refer here.

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

<TextBox Margin="0,287,0,0">
     <i:Interaction.Triggers>
          <i:EventTrigger EventName="LostFocus">
               <i:InvokeCommandAction Command="{Binding LostFocusCommand}" />
          </i:EventTrigger>
     </i:Interaction.Triggers>
</TextBox>
Community
  • 1
  • 1
Selva
  • 976
  • 1
  • 10
  • 23
  • Gives Compilations Errors like "Trigger was not found in Interection" as well as "Invoke command doesn't exist in namespace http://schemas.microsoft.com/expression/2010/interactivity" – Pratik Aug 06 '14 at 07:05
  • download the dll from http://www.codeproject.com/Articles/125188/Using-EventTrigger-in-XAML-for-MVVM-No-Code-Behind – Selva Aug 06 '14 at 07:08
  • Sry actually I was in hurry and I got your reply too late. – Pratik Aug 08 '14 at 02:06