Execute a method on second control from the first control in WPF

早过忘川 提交于 2019-12-25 01:16:26

问题


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.


回答1:


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:

public class EventTriggerWrapper
{
    public event EventHandler OnTriggered;

    public void Trigger()
    {
        this.OnTriggered?.Invoke(this, EventArgs.Empty);
    }
}

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:

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition />
    </Grid.RowDefinitions>

    <Button Content="Click Me" Command="{Binding NavigateCommand}" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10" />        

    <WebBrowser Grid.Row="1">
        <i:Interaction.Behaviors>
            <behaviors:MyCustomBehavior EventTrigger="{Binding EventTrigger}" />
        </i:Interaction.Behaviors>
    </WebBrowser>

</Grid>

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:

public class MainViewModel
{
    public EventTriggerWrapper EventTrigger { get; } = new EventTriggerWrapper();

    private ICommand _NavigateCommand;
    public ICommand NavigateCommand => this._NavigateCommand ?? (this._NavigateCommand = new RelayCommand(OnNavigate));

    private void OnNavigate()
    {
        this.EventTrigger.Trigger();
    }
}

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:

public class MyCustomBehavior : Behavior<WebBrowser>
{
    public EventTriggerWrapper EventTrigger
    {
        get { return (EventTriggerWrapper)GetValue(EventTriggerProperty); }
        set { SetValue(EventTriggerProperty, value); }
    }

    // Using a DependencyProperty as the backing store for EventTrigger.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty EventTriggerProperty =
        DependencyProperty.Register("EventTrigger", typeof(EventTriggerWrapper), typeof(MyCustomBehavior), new PropertyMetadata(null, OnEventTriggerChanged));

    private static void OnEventTriggerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var behaviour = d as MyCustomBehavior;
        var oldValue = e.OldValue as EventTriggerWrapper;
        if (oldValue != null)
            oldValue.OnTriggered -= behaviour.OnEventTriggered;
        var newValue = e.NewValue as EventTriggerWrapper;
        if (newValue != null)
            newValue.OnTriggered += behaviour.OnEventTriggered;
    }

    private void OnEventTriggered(object sender, EventArgs e)
    {
        if (this.AssociatedObject != null)
            this.AssociatedObject.Navigate("http://www.google.com");    // <-- change this to the function you want to invoke
    }
}


来源:https://stackoverflow.com/questions/56312349/execute-a-method-on-second-control-from-the-first-control-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!