My ViewControl has a method called ZoomIn(). How can I execute this method on the ViewControl by clicking a Button control without going to the code-behind?
<controls:ViewControl/>
<Button Content="Zoom In"/>
Here is the code for ViewControl.xaml.cs:
public void ZoomIn()
{
double actualWidth = m_child.ActualWidth;
double actualHeight = m_child.ActualHeight;
double x = (0.5 * actualWidth - Dx) / Scale;
double y = (0.5 * actualHeight - Dy) / Scale;
float startScale = Scale;
Scale = Math.Min(Scale * ZoomFactor, ZoomMax);
Dx = (float)x * (startScale - Scale) + Dx;
Dy = (float)y * (startScale - Scale) + Dy;
}
I am trying to use MVVM for my design, but I'm not sure how to do this in this scenario because the ZoomIn() method is related to the View.
A similar situation would be if I had a Button and a TextBox, and I wanted to call the SelectAll() method on the TextBox when the Button is clicked. How can I do this without using the code-behind?
There are actually several different ways to do this, one solution is to bind to an event using a behavior and a wrapper class. First define a wrapper for the event that your view model will trigger:
For the purpose of demonstration here's some XAML of a button and a WebBrowser, I'll use an instance of the wrapper in the view model to trigger the web broswer's
Navigate()function whenever the button is pressed:You can see that I've added a custom behaviour to the web browser control, and it's bound to a view model property called
EventTrigger. You'll need to add this along with a command handler for the button to your view model:So all that's left it to create the behavior with a property that subscribes to the event and then calls whatever function in your target control you want: