WPF Binding FrameworkElement event to command

混江龙づ霸主 提交于 2020-01-14 03:29:11

问题


How can I bind a UserControl's FrameworkElement event to a view model command? I use MVVM and Prism so clear separation between the view the view-model would be nice.

I'd tried multiple things, and none of them worked:

<i:Interaction.Triggers>
    <i:EventTrigger EventName="FrameworkElement.Unloaded">
        <i:InvokeCommandAction Command="{Binding Unloaded}" />
    </i:EventTrigger>
</i:Interaction.Triggers>

also using this tutorial http://blog.functionalfun.net/2008/09/hooking-up-commands-to-events-in-wpf.html

local:FrameworkElementBehavior.UnloadedCommand="{Binding Unloaded}"

Do I have no choice but to add some functions to my code-behind?

Neither of the attempts above error out, but the command does not execute.

Here's my view model:

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");
        }
    }
}

回答1:


I think the problem could be in Unloaded event.

From MSDN page http://msdn.microsoft.com/en-us/library/ms754221.aspx#common_events:

Unloaded is raised last and is initiated by either the presentation source or the visual parent being removed. When Unloaded is raised and handled, the element that is the event source parent (as determined by Parent property) or any given element upwards in the logical or visual trees may have already been unset, meaning that data binding, resource references, and styles may not be set to their normal or last known run-time value.



来源:https://stackoverflow.com/questions/10934040/wpf-binding-frameworkelement-event-to-command

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