WPF Binding FrameworkElement event to command

2019-06-04 22:08发布

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条回答
倾城 Initia
2楼-- · 2019-06-04 22:56

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.

查看更多
登录 后发表回答