My ViewControl
has a method called ZoomIn()
. How can I execute this method on this ViewControl
by clicking Button
control without going to code-behind.
<controls:ViewControl/>
<Button Content="Zoom In"/>
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;
}
Although I have a ViewModel and trying to use MVVM for my design. I am not sure how it is possible in this scenario as the ZoomIn() does something that is View-related.
A similar case I can think of is when I have a Button and a TextBox and I want to call SelectAll() method on TextBox when clicking Button.
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: