是否可以将 WPF 事件绑定到 MVVM ViewModel 命令?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25136383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to bind a WPF Event to MVVM ViewModel command?
提问by user1890098
I have a xaml window and on the StateChanged event of the window I have to execute a piece of code. I have to follow MVVM. I binded the StateChanged property to an ICommand? It doesn't work.
我有一个 xaml 窗口,在窗口的 StateChanged 事件上我必须执行一段代码。我必须遵循MVVM。我将 StateChanged 属性绑定到 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}">
This is my viewmodel.
这是我的视图模型。
public ICommand IsMinimized
{
get
{
if (_IsMinimized == null)
{
_IsMinimized = new RelayCommand(param => this.OnMinimized(), null);
}
return _IsMinimized;
}
}
private void OnMinimized()
{
//do something here
}
Is there anyother way to do this?
有没有其他方法可以做到这一点?
回答by esskar
Yes, you can bind events to your model, but you need help. You need to use functions from the System.Windows.Interactivity Namespaceand include a MVVM Light(there might be other MVVM libraries that have that feature but i use MVVM Light).
是的,您可以将事件绑定到您的模型,但您需要帮助。您需要使用System.Windows.Interactivity 命名空间中的函数并包含一个MVVM Light(可能还有其他 MVVM 库具有该功能,但我使用 MVVM Light)。
Include the following namespaces to your window
将以下命名空间包含在您的窗口中
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras"
and bind your events like
并绑定您的事件,例如
<i:Interaction.Triggers>
<i:EventTrigger EventName="StateChanged">
<cmd:EventToCommand Command="{Binding StateChangedCommand}" PassEventArgsToCommand="True" />
</i:EventTrigger>
</i:Interaction.Triggers>
HTH
HTH
回答by user1890098
Thanks for the all the help. But I ended up binding WindowState to a property and handled the code there.
感谢所有的帮助。但我最终将 WindowState 绑定到一个属性并在那里处理代码。
public WindowState CurrentWindowState
{
get { return _currentWindowState; }
set
{
_currentWindowState = value;
if (_currentWindowState == WindowState.Minimized) //any other clause here
{
//do something here
}
NotifyPropertyChanged("CurrentWindowState");
}
}

