如何将 UserControl
的 FrameworkElement
事件绑定(bind)到 View 模型命令?我使用 MVVM 和 Prism,因此 View 和 View 模型之间的清晰分离会很好。
我尝试了多种方法,但都不起作用:
<i:Interaction.Triggers>
<i:EventTrigger EventName="FrameworkElement.Unloaded">
<i:InvokeCommandAction Command="{Binding Unloaded}" />
</i:EventTrigger>
</i:Interaction.Triggers>
也使用本教程 http://blog.functionalfun.net/2008/09/hooking-up-commands-to-events-in-wpf.html
local:FrameworkElementBehavior.UnloadedCommand="{Binding Unloaded}"
我别无选择,只能在我的代码隐藏中添加一些函数吗?
上述尝试均未出错,但命令未执行。
这是我的 View 模型:
public class CustomerViewModel : PosViewModelBase
{
public ICommand Unloaded
{
get { return new UnloadedCommand(); }
}
public CustomerViewModel()
{
}
private class UnloadedCommand : ICommand
{
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
Debug.WriteLine("Customer stuff is out of view");
}
}
}
最佳答案
我认为问题可能出在 Unloaded 事件中。
来自 MSDN 页面 http://msdn.microsoft.com/en-us/library/ms754221.aspx#common_events :
Unloaded 最后引发,并由演示源或正在删除的视觉父对象启动。当 Unloaded 被引发和处理时,作为事件源父元素(由 Parent 属性确定)的元素或逻辑树或可视树中向上的任何给定元素可能已被取消设置,这意味着数据绑定(bind)、资源引用和样式可能已被取消设置。未设置为其正常值或最后已知的运行时值。
关于WPF 将 FrameworkElement 事件绑定(bind)到命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10934040/