Home > OS >  How to use Interaction Triggers for maximizing and minimizing WPF window using c# with mvvm pattern?
How to use Interaction Triggers for maximizing and minimizing WPF window using c# with mvvm pattern?

Time:09-23

I can close a window using Interaction Triggers like

            <Button Content="X" Height="20" Width="20">
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="Click">
                        <i:CallMethodAction MethodName="Close"
                            TargetObject="{Binding RelativeSource={RelativeSource
                        Mode=FindAncestor,
                        AncestorType=Window}}" />
                    </i:EventTrigger>
                </i:Interaction.Triggers>
            </Button>

But when I replace MethodName="Close" with MethodName="Maximize" or MethodName="Minimize" to maximize or minimize window it doesn't work.

How do I do this using .Net 4.5 without breaking mvvm pattern ?

CodePudding user response:

MethodName="Close" works because there is Close() method in Window type, but there is no Maximize() or Minimize() methods out there, these are states, there is WindowState property that you can set to Minimize or Maximize..

  1. You can change it explicitly when the button is clicked
void Button_OnClick(object sender, RoutedEventArgs e)
{
    this.WindowState = Maximize;
}
  1. Or you can define your own window that has Minimize() and Maximize() methods..
public class MyWindow : Window {

    public void Maximize(){
        this.WindowState = Maximize;
    }
    
    public void Minimize(){
        this.WindowState = Minimize;
    }
}

And in .xaml

<views:MyWindow [views namespace here]..
    <!-- -->
    <Button Content="X" Height="20" Width="20">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="Click">
                <i:CallMethodAction MethodName="Maximize"
                    TargetObject="{Binding RelativeSource={RelativeSource
                Mode=FindAncestor,
                AncestorType=MyWindow}}" />
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </Button>
    <!-- -->
</Window>
  • Related