首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用mvvm在WPF网格或用户控件上绑定聚焦事件?

如何使用mvvm在WPF网格或用户控件上绑定聚焦事件?
EN

Stack Overflow用户
提问于 2018-08-09 05:39:13
回答 1查看 0关注 0票数 0

我有一个由第三方应用程序托管的wpf用户控件作为非模态可停靠窗口。我想在窗口获得焦点或鼠标进入窗口时触发事件。

这是一个MVVM设计。如何将Grid或UserControl的事件处理程序绑定到viewmodel上的方法。我想避免使用xaml.cs代码,因为我必须将datacontext转换为预期的viewmodel来进行调用。

代码语言:javascript
复制
<UserControl x:Class="MVVMWithCommand.ChartExtentView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:MVVMWithCommand"
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300" GotFocus="UserControl_GotFocus">
<UserControl.DataContext>
    <local:MyViewModel/>
</UserControl.DataContext>
<Grid GotFocus="Grid_GotFocus">
EN

回答 1

Stack Overflow用户

发布于 2018-08-09 15:37:45

你可以通过在XAML中添加以下两行来实现此目的:

代码语言:javascript
复制
xmlns:intr="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" 
xmlns:cmd="http://www.galasoft.ch/mvvmlight"

你还需要将MvvmLightLibsNuget-Explorer添加到项目中。

然后,你可以使用EventToCommand功能将事件绑定到ViewModel中的命令。

代码语言:javascript
复制
<Grid>
    <intr:EventTrigger EventName="GotFocus">
        <cmd:EventToCommand Command="{Binding GotFocusCommand}"
                                        PassEventArgsToCommand="True" />
    </intr:EventTrigger>
</Grid>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100005944

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档