WPF event binding from View to ViewModel?

隐身守侯 提交于 2019-12-17 10:44:51

问题


Whats the best way to bind a WPF event in the View to the ViewModel?

I got a drop event in my View but I want to replace it to the ViewModel due binding. Found several solutions but none of them did what I aspected.

View code:

    <TextBox 
    AllowDrop="True" 
    PreviewDrop="email_Drop" />

回答1:


One way to handle events in MVVM and XAML is to use the Blend Interactivity features. This namespace contains the InvokeCommandAction and the CallMethodAction classes.

InvokeCommandAction lets you bind any event to a view-model command while CallMethodAction lets you bind any event to a view-model method.

For example if you want to bind the DoubleClick event of a Button to a view-model command you would do like this:

<Button>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="MouseDoubleClick">
            <i:InvokeCommandAction Command="{Binding Path=DoSomethingCommand}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Button>

And declaring this namespace:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

All you need to reference it in your projects is to install Expression Blend or the Expression Blend SDK.




回答2:


Well one way to do is to convert that event into a command and then bind it to presenter command, i.e. by defining event behaviour.

See this, WPF Event Binding to ViewModel (for non-Command classes)




回答3:


<Button MouseDoubleClick="{eb:EventBinding Command=DoSomethingCommand}">

</Button>

Command

{eb:EventBinding} (Simple naming pattern to find Command)

{eb:EventBinding Command=CommandName}

CommandParameter

$e (EventAgrs)

$this or $this.Property

string

https://github.com/JonghoL/EventBindingMarkup




回答4:


I get the viewmodel from the bindingcontext and activate my viewmodel method from there

    public partial class ParentView : ContentPage
    {
            public ParentView()
            {            
                InitializeComponent();
            }

            private void LanguagePicker_SelectedIndexChanged(object sender, System.EventArgs e)
            {
                var parentViewModel = (ParentViewModel)this.BindingContext;
                parentViewModel.SelectedLanguageChanged(sender,e);
            }
    }


来源:https://stackoverflow.com/questions/7877532/wpf-event-binding-from-view-to-viewmodel

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