我有一个xaml窗口,在窗口的StateChanged事件上,我必须执行一段代码。我必须遵循MVVM。我将statechange属性绑定到一个ICommand?这行不通。
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="DummyApp"
x:Name="Window"
Title="Dummy App"
Width="{Binding WindowWidth,Mode=OneWayToSource}" Height="{Binding WindowHeight}" ResizeMode="CanMinimize" Icon="Logo.png" SizeToContent="WidthAndHeight" WindowStartupLocation="CenterScreen" WindowState="{Binding CurrentWindowState, Mode=TwoWay}"
ShowInTaskbar="{Binding ShowInTaskBar, Mode=TwoWay}" StateChanged="{Binding IsMinimized}">
这是我的视图模型。
public ICommand IsMinimized
{
get
{
if (_IsMinimized == null)
{
_IsMinimized = new RelayCommand(param => this.OnMinimized(), null);
}
return _IsMinimized;
}
}
private void OnMinimized()
{
//do something here
}
还有别的方法吗?
谢谢大家的帮助。但我最终将WindowState绑定到一个属性,并在那里处理代码。
public WindowState CurrentWindowState
{
get { return _currentWindowState; }
set
{
_currentWindowState = value;
if (_currentWindowState == WindowState.Minimized) //any other clause here
{
//do something here
}
NotifyPropertyChanged("CurrentWindowState");
}
}
是的,您可以将事件绑定到您的模型,但是您需要帮助。你需要使用来自System.Windows.Interactivity命名空间的函数,并包含MVVM Light(可能有其他MVVM库具有该功能,但我使用MVVM Light)。
在您的窗口
中包含以下名称空间xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras"
并像
那样绑定事件<i:Interaction.Triggers>
<i:EventTrigger EventName="StateChanged">
<cmd:EventToCommand Command="{Binding StateChangedCommand}" PassEventArgsToCommand="True" />
</i:EventTrigger>
</i:Interaction.Triggers>
HTH